admin管理员组

文章数量:1312655

I have an input field that gets pre-populated from my DB, but I won't want it to be pre-filled if the value is 0

Eg:

<input v-model="price" type="text">

If

  data: {
 price: 0
}

I don't want my input field to display 0, I know that I can do stuff like :disabled="price == 0" but this will hide the whole input field, I just don't want to display the value if its 0

I have an input field that gets pre-populated from my DB, but I won't want it to be pre-filled if the value is 0

Eg:

<input v-model="price" type="text">

If

  data: {
 price: 0
}

I don't want my input field to display 0, I know that I can do stuff like :disabled="price == 0" but this will hide the whole input field, I just don't want to display the value if its 0

Share Improve this question edited Aug 13, 2020 at 7:23 MendelG 20.1k5 gold badges36 silver badges63 bronze badges asked Aug 29, 2017 at 10:57 user2722667user2722667 8,66114 gold badges60 silver badges103 bronze badges 2
  • What about programatically changing the value from 0 to "" in the model? Would that work? – Borjante Commented Aug 29, 2017 at 10:59
  • you could try something like this: price !== 0 – codejockie Commented Aug 29, 2017 at 11:07
Add a ment  | 

2 Answers 2

Reset to default 6

Simply change price to empty string when it's 0:

created() {
    //since 0 is considered false it will put an empty string in case priceFromDB is 0
    this.price = priceFromDB || ''
  }

As I understood you want to always have empty input when value of price is 0, even if user type It manually.If that's true, something like this should work for you:

<div id="app">
    <input type="text" v-model="price" @keyup="trackChange">
</div>

JS:

const app = new Vue({

  el: '#app',

  data: {
    price: 0
  },

  methods: {
    trackChange() {
      this.price = parseInt(this.price) === 0  ? null : this.price
    }
  },

  created() {
    this.trackChange()
  }


})

Demo: http://jsbin./sihuyotuto/edit?html,js,output

本文标签: javascriptVueJS dont display input value if its 0Stack Overflow