The Bassman
The Bassman

Reputation: 2361

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

Upvotes: 1

Views: 1600

Answers (2)

Phil
Phil

Reputation: 164897

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/[email protected]/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>

Upvotes: 4

Azad
Azad

Reputation: 5272

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>

Upvotes: 0

Related Questions