I am trying to use a Vue watcher on a computed object and it is not working at all. It works properly if its just a string, but not if its an object. I followed the Vue documentation but I am still getting nothing logged to the console when the object changes. The properties of the object and computed property is changing, as I have confirmed in Vue Tools. What am I doing wrong? Thanks
<v-btn small dark @click="test1.asdf = 'blah'">Test</v-btn>
data() {
return {
test1: {},
}
},
computed: {
test(){
return this.test1
}
},
watch: {
test: {
handler: function(val, oldVal) {
console.log(oldVal, val);
},
deep: true
}
}
CodePudding user response:
Try this code, its works fine
<template>
<div id="app">
{{ test1 }}
<hr />
<button @click="test1.asdf = 'blah'">Click</button>
</div>
</template>
<script >
export default {
data() {
return {
test1: { asdf: "HEY" },
};
},
computed: {
test() {
return this.test1;
},
},
watch: {
test: {
handler: function (val, oldVal) {
console.log(oldVal, val);
},
deep: true,
},
},
};
</script>
I'd guess in your case you should add .native
at end of your click event like this @click.native="test1.asdf = 'blah'"
CodePudding user response:
Just tried by replacing the whole object. It works pretty well, and there is no need to initialize your object with the asdf
property in your data:
<v-btn small dark @click="test1 = { ...test1, asdf: 'blah'}">Test</v-btn>
The spread syntax ...test1
helps keeping other properties in the target object if there is any, so you can safely add the asdf
property without worrying about losing anything.
JSFiddle: https://jsfiddle.net/vh72a3bs/22/