Search code examples
javascriptdata-bindingvue.jsbidirectional

Transform v-model bound value in Vue.js


Consider this example:

<input type="text" v-model="value">
<span>Value is: {{ value }}</span>

What I want is to put a bidirectional transformation function that would present the value in the input field in one form, but keep it in the data in another form. The simplest example would be negating numeric values: if the user inputs 5, I'd like the data to actually receive −5. What would be the best way of accomplishing that in Vue.js 1.0?


Solution

  • You could use watchers for this.

    Every time the input value changes, the watcher will update the data property value in any way you want. The input display value will stay the same, but your data property will have the new manipulated value.

    For ex.:

    new Vue({
      el: "#app",
      data: {
        value: 0,
        display_value: 0
      },
      watch: {
          display_value: function (newValue) {
              this.value = -parseInt(newValue);
          }
      }
    })
    

    And your html:

    <input type="text" v-model="display_value">
    <span>Value is: {{ value }}</span>
    

    Fiddle: https://jsfiddle.net/crabbly/30e6h4uj/