[Vuejs]-Transform v-model bound value in Vue.js

6๐Ÿ‘

โœ…

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/

๐Ÿ‘คcrabbly

13๐Ÿ‘

You can just write a computed property for that:

new Vue({
  el: "#app",
  data: {
    value: 0
  },
  computed: {
    negValue() {return -this.value}
  }
})

And then the template becomes

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

https://jsfiddle.net/adf2kLhe/

๐Ÿ‘คgurghet

1๐Ÿ‘

You can use a watcher to set negValue

new Vue({
  el: "#app",
  data: {
    value: 0,
    negValue: 0
  },
  watcher: {
    value(value) {this.negValue = -value}
  }
})

Then:

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

When you send it to server, just send negValue instead of value.

๐Ÿ‘คAlex M.

Leave a comment