监听器
watch与data和methods同级
watch 监听data中属性的改变
const vm = new Vue({
el: '#app',
data: {
firstValue: '',
endValue: '',
// value: ' ',
obj: {
name: 'zs'
}
},
methods: {
// add() {
// this.value = this.firstValue + '-' + this.endValue
// }
changeObj() {
this.obj.name = 'ls'
console.log(this.obj.name);
}
},
//watch 监听data中属性的改变
watch: {
obj: {
handler(val) {
console.log(val);
},
deep: true
},
firstValue: {
handler(newVal, oldVal) {
console.log(newVal);
console.log(oldVal);
},
// immediate 立即执行监听
immediate: true,
// deep 深度监听
deep: true
}
}
})
计算属性
computed 中的元素不能再data中定义
computed与data和methods同级
const vm = new Vue({
el: '#app',
data: {
firstValue: '',
endValue: '',
// value: ' ',
obj: {
name: 'zs'
}
},
methods: {
// add() {
// this.value = this.firstValue + '-' + this.endValue
// }
changeObj() {
this.obj.name = 'ls'
console.log(this.obj.name);
}
},
computed: {
value: {
get() {
return this.firstValue + '-' + this.endValue
},
set(val) {
console.log(val);
console.log(val.split('-'));
this.firstValue = val.split('-')[0]
this.endValue = val.split('-')[1]
}
}
}
})
methods watch 和computed的区别
1、computed属性的结果会被缓存,除非依赖的响应式属性变化才会重新计算。主要当作属性来使用,使用的时候不加();
2、methods方法表示一个具体的操作,主要书写业务逻辑;
3、watch一个对象,键是需要观察的表达式,值是对应回调函数。主要用来监听某些特定数据的变化,从而进行某些具体的业务逻辑操作,可以看作是computed和methods的结合体。