I’m playing around with Vue, and I’ve seen you can set up a ‘watch’ callback for when a piece of Data changes:
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<input v-model="inputVal" placeholder="edit me" />
<p>{{ inputVal }}</p>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
},
data() {
return {
inputVal: '22'
}
},
watch: {
inputVal: function(val, oldVal) {
console.log('inputVal changed');
console.log(oldVal);
console.log(val);
}
}
}
</script>
If I want to make a change to the data state inside the watch.inputVal
function, how would I do that?
2
Answers
It’s pretty simple:
But generally if some of your state is dependent on some other state, it might be a better idea to use computed instead of watch:
Computed is lazy, cached and overall easier to understand. The main purpose of watch is to execute side effects.
Inside the watch you can access
data
object usingthis
keyword. To make changes todata
object you can update usingthis.propertyName = newValue
.In this code we have new data state named
anotherState
, it gets updated wheneverinputVal
is changed. I am not sure if I got your question correctly. Is that something you were looking for?