我有这个非常基本的 HTML:
<div id="app">
<input type="number" @change="start=$event.target.value">
<input type="number" @change="final=$event.target.value">
<button v-bind:disabled="isButtonActive">Proceed</button>
{{start}} -- {{final}} -- {{res}}
</div>
Run Code Online (Sandbox Code Playgroud)
和小的 vue.js 代码:
new Vue({
el: '#app',
data: {
start: 0,
final: 0
},
computed: {
res() {
return this.start < this.final;
}
},
methods: {
isButtonActive() {
return this.start < this.final;
}
}
})
Run Code Online (Sandbox Code Playgroud)
现在的问题是:如果我将 2 输入第一个输入,将 12 输入第二个,我得到了
'2 -- 12' -- false,但为什么 - 2 < 12?
如果我先把 12 放到第二个输入,然后把 2 放到第一个我得到
'2 -- 12 -- true'
Run Code Online (Sandbox Code Playgroud)
如果我将 2 改为 45 我得到了
'45 -- 12 -- true',哦
现在,“真”或“假”按钮永远不会变为活动状态。请帮忙。这是codepen链接
因为 的值$event.target.value是一个字符串,而不是数字,您可以通过parseInt将字符串转换为数字。检查下面的演示。
Vue.config.productionTip = false
new Vue({
el: '#app',
data: {
start: 0,
final: 0
},
computed: {
res() {
console.log(typeof this.start, typeof this.final, this.start < this.final)
console.log('[Use ParseInt]', parseInt(this.start) < parseInt(this.final))
return this.start < this.final;
}
},
methods: {
isButtonActive() {
return this.start < this.final;
}
}
})Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
<div id="app">
<input type="number" @change="start=$event.target.value">
<input type="number" @change="final=$event.target.value">
<button v-bind:disabled="isButtonActive">Proceed</button>
{{start}} -- {{final}} -- {{res}}
</div>Run Code Online (Sandbox Code Playgroud)
您可以使用modifier = v-model.number那么您应该v-bind:disabled使用isButtonActive()函数的result( ) 而不是函数本身( isButtonActive),否则使用v-bind:disabled="res" 会更好。(计算属性和方法之间的区别在于计算属性是根据它们的依赖关系缓存的),您可以点击单击我按钮查看差异。
像下面的演示:
Vue.config.productionTip = false
new Vue({
el: '#app',
data: {
start: 0,
final: 0,
testText: 'You will see isButtonActive is invoked, but computed properties will not'
},
computed: {
res() {
console.log('computed=res', typeof this.start, typeof this.final)
return this.start < this.final;
}
},
methods: {
isButtonActive() {
console.log('isButtonActive', typeof this.start, typeof this.final)
return this.start < this.final;
},
test: function () {
this.testText += '!'
}
}
})Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
<div id="app">
<input type="number" v-model.number="start">
<input type="number" v-model.number="final">
<button v-bind:disabled="isButtonActive()">Proceed</button>
<button v-bind:disabled="res">Proceed</button>
{{start}} -- {{final}} -- {{res}}
<hr>
<button @click="test()">Click me!!!</button>
<p>{{testText}}</p>
</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11890 次 |
| 最近记录: |