Null 和空字符串在我的代码中给出了不同的结果:
<b-button :disabled="phone && phone.length < 9"></b-button>
phone
变量设置为 null
:
data () {
return {
phone: null
}
在本例中phone
等于 false,因此我的 && phone.length < 9
据我了解,声明不会触发。
但是如果我设置 phone: ''
(空字符串),然后是我的phone
设置为true
并触发下一条语句 && phone.length < 9
.
此条件的目的是禁用按钮,如果 phone
号码为空,或少于 9 位数字。
最佳答案
您可以使用计算属性来轻松检查输入:
var app = new Vue({
el: '#app',
data: {
phone: null,
inputText: null
},
computed: {
isDisabled() {
return (this.phone ? this.phone.length < 9 : true)
}
}
})
<script src="https://cdn.jsdelivr.net/npm/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0d6d5c5e0928e958e9197" rel="noreferrer noopener nofollow">[email protected]</a>/dist/vue.js"></script>
<div id="app">
<input type="text" v-model="phone" />
<br /> phone: {{ phone }}
<br /> isDisabled: {{ isDisabled }}
</div>
直接在按钮上使用计算属性:
<b-button :disabled="isDisabled"></b-button>
顺便说一句:如果您打算进行更高级的表单验证,可以使用易于使用的库,例如 VeeValidate .
关于javascript - null 与空字符串,不同的结果 - Vue2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52502284/