0

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?

2
  • so you mean formatting the input such that, it appears 5 but is -5? Commented Apr 10, 2017 at 10:04
  • @AmreshVenugopal Yeah, pretty much. Commented Apr 10, 2017 at 10:08

3 Answers 3

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/

Sign up to request clarification or add additional context in comments.

2 Comments

That only negates the presentation of the value; data.value isn't negated. I need to negate the data, not the presentation of it, because the data then gets posted to the server side and that is where the minus sign is required.
Just post negValue instead of value I don’t see the problem.
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/

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.