vue js watch multiple properties with single handler
export default {
// ...
computed: {
propertyAAndPropertyB() {
return `${this.propertyA}|${this.propertyB}`;
},
},
watch: {
propertyAAndPropertyB(newVal, oldVal) {
const [oldPropertyA, oldProvertyB] = oldVal.split('|');
const [newPropertyA, newProvertyB] = newVal.split('|');
// doSomething
},
},
}
或者
new Vue({
el: '#app',
data: {
name: 'Alice',
surname: 'Smith',
fullName: '' // IRL you would use a computed for this, I'm updating it using a watch just to demo how it'd be used
},
mounted() {
this.$watch(vm => [vm.name, vm.surname], val => {
this.fullName = this.name + ' ' + this.surname;
}, {
immediate: true, // run immediately
deep: true // detects changes inside objects. not needed here, but maybe in other cases
})
}
});