VueJS:如何设置输入的模型而不必将其放在输入上 [英] VueJS: How to set model of an input without having it to be on the input
本文介绍了VueJS:如何设置输入的模型而不必将其放在输入上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望输入在视图侧的元素上没有任何值,但在下面我希望它具有默认值,这里有一些片段来解释我的观点:
I want an input to have no value on it's element on the view side but underneath I want it to have a default value, here is some snippet to explain my point:
<input
class="form-control"
v-model="amount"
type="number"
step=".01"
min="0"
required>
</input>
我希望金额默认为 0 但不在输入上呈现 0,这在 vuejs 中可行吗?如果 input[type="number"] = ''
,则该属性的值为 0 而不是 ' '.
I want amount to be 0 by default but not render 0 on the input, is this possible in vuejs? If the input[type="number"] = ''
, the value of the property is 0 and not ' '.
推荐答案
您可以将计算属性与 getter 和 setter 一起使用.如果值为零,getter 可以返回一个空字符串...
You can use a computed property with getter and setter. The getter can return an empty string if the value is zero...
new Vue({
el: 'main',
data: {
amount: 0
},
computed: {
formattedAmount: {
get () {
return this.amount || ''
},
set (value) {
this.amount = parseFloat(value) || 0
}
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.min.js"></script>
<main>
<input class="form-control" v-model="formattedAmount" type="number" step=".01" min="0" placeholder="Amount" required/>
<pre>amount = {{ amount }}</pre>
</main>
这篇关于VueJS:如何设置输入的模型而不必将其放在输入上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文