VueJS: How to set model of an input without having

2019-08-17 05:56发布

问题:

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? If the input[type="number"] = '', the value of the property is 0 and not ' '.

回答1:

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>



回答2:

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>