0

I have an input that uses the v-model directive to control the data. I need to watch said data and figure out if it's been changed.

When I watch the data, the new and old values are the same. This is because the data is mutated, as seen in the docs: https://vuejs.org/v2/api/#vm-watch

Note: when mutating (rather than replacing) an Object or an Array, the old value will be the same as new value because they reference the same Object/Array. Vue doesn’t keep a copy of the pre-mutate value.

How do I use v-model and NOT mutate the data?

chrki
  • 5,626
  • 6
  • 28
  • 51
Gurnzbot
  • 2,190
  • 3
  • 25
  • 44
  • What is the reason for watching the property? A `v-model` is essentially nothing but syntactic sugar for `:value=""` and `@input=""` within the `@input` you can specify a custom method and hook into the changes. – Stephan-v Oct 03 '18 at 14:27

1 Answers1

0

You could use a separate data value to track changes with $watch, rather than using the model bound variable. This gives you access to the previous value.

HTML

<div id="app">
    <input v-model="inputModel" type="text" />
</div>

Javascript

var vm = new Vue({
    "el" : "#app",
    "data" : {
            "inputModel" : "",
            "inputValue" : ""
    },
    "methods" : {
        "changeHandler" : function(a,b) {
            console.log("Updating \""+this.inputValue+"\" to \""+a+"\"");
            this.inputValue = a;
        }
    }
});

vm.$watch("inputModel",vm.changeHandler);
user3357118
  • 684
  • 4
  • 13
  • close. but you should use a computed value that compares `inputModel` to `inputValue`. That way you maintain the original value. – Justin Kahn Oct 03 '18 at 14:13