简体   繁体   English

VueJS:如何设置输入模型而不将其放在输入中

[英]VueJS: How to set model of an input without having it to be on the input

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>

I want amount to be 0 by default but not render 0 on the input, is this possible in vuejs? 我想让数量默认为0,但不要在输入上呈现0,这在vuejs中可行吗? If the input[type="number"] = '' , the value of the property is 0 and not ' '. 如果input[type="number"] = '' ,则该属性的值为0而不是''。

You can use a computed property with getter and setter. 您可以将计算属性与getter和setter一起使用。 The getter can return an empty string if the value is zero... 如果值为零,则getter可以返回一个空字符串。

 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> 

you can bind the model values 您可以绑定模型值

 var myObject = new Vue({ el: '#app', data: { amount: 0 } }) 
 <!DOCTYPE html> <html> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <body> <div id="app"> <input class="form-control" v-model="amount" type="number" step=".01" min="0" required> </input> </div> </body> </html> 

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

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