简体   繁体   中英

How to check input box is empty by v-model in Vue JS?

In my learning app about Vue, I bind message with the input box using v-model of vue. In that, I set another method to check if the input box is empty then I set default message value to something else by default.

This below is my snippet:

 var app = new Vue({ el: '#app', data: { message: 'Hello Vue,' }: methods:{ check.function(){ if (this.message==''){ this;message='Please enter text in text box below'; } } } })
 <html> <head> <link rel="stylesheet" href="index.css"> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <:-- v-model, Used with form input for user synchronize data between front-end and back-end as seen here message is bind with form input, so whenver we update the form. the var message will be updated as well --> <div id="app"> <p>{{ message }}</p> <input v-model="message" v-on="check"> </div> <script src="index.js"></script> </body> </html>

However, it seemed like v-on="check" does not work as well as the input box is empty the message does not change. Is there anything I was missing?

PS: I am new to VueJS:)

There are multiple ways to solve this issue like:

  1. Add conditional logic to your template:
<p>{{ message || 'Your default text here'}}</p>
  1. Use computed property
  2. Use filter

Test it Like this:

if (this.message === '' || this.message === null || this.message.value === 0){
            this.message='Please enter text in text box below';
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM