简体   繁体   English

如何在Vue JS中通过v-model检查输入框是否为空?

[英]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.在我关于 Vue 的学习应用程序中,我使用 vue 的v-modelmessage与输入框绑定。 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.在那,我设置了另一种方法来检查输入框是否为空,然后我将默认message值默认设置为其他值。

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.但是,似乎v-on="check"不起作用以及输入框为空message不会改变。 Is there anything I was missing?我有什么遗漏吗?

PS: I am new to VueJS:) PS:我是 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';
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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