Search code examples
vue.jsinputv-model

How do I replicate v-models :value with :value?


I get different behavior between using @input and v-model, and @input and :value.

What is v-model doing different with :value that I dont get with only using :value?

I created an example at jsFiddle that show the difference: that the top input field would allow only numbers to be typed into the input, while the bottom will allow everything to be typed in.

What do I need to do to get the same functionality by using only @input and :value?


Solution

  • You can achieve this by adding an ref to the input and updating input value through it. Check here. https://jsfiddle.net/RiddhiParekh/nzfr0xy3/

    Template =>

        <div id="app">
      <div>
        <input @input="mask1" 
               v-model="message1" 
               type="text" 
               placeholder="Only numbers are allowed">
        <p>Message1 is: {{ message1 }}</p>
        <hr/>
        <input @input="mask2" 
               :value="message2"
               type="text"
               ref="myInput"
               placeholder="Try numbers">
        <p>Message2 is: {{ message2 }}</p>
    
      </div>
    </div>
    

    Script =>

     new Vue({
      el: "#app",
      data: {
       message1: "",
       message2: ""
      },
      methods: {
        mask1(input){
            const validCharsForNumberFields = /[0-9]*(,|\.)?[0-9]*/gm
          this.message1 = input.target.value.match(validCharsForNumberFields)[0]
            },
        mask2(input){
          const validCharsForNumberFields = /[0-9]*(,|\.)?[0-9]*/gm
          console.log(input)
          this.$refs.myInput.value = input.target.value.match(validCharsForNumberFields)[0]
          this.message2 = this.$refs.myInput.value
        },
    
      }
    })