1.watch侦听器
用于观察和监听页面上的vue实例,当需要在数据变化时执行异步或开销较大的操作时可使用,需要在data()先定义。
执行顺序:beforeCreate-watch-created。
watch: {
firstName: function (newVal,oldVal) {
console.log("第一次没有执行");
this.fullName = newVal + "·" + this.lastName;
},
lastName:function(val){
this.fullName = this.firstName+val
}
}
watch的handler方法和immediate属性
watch第一次不会执行,需要加handler方法和immediate: true第一次才会执行。
watch: {
firstName: {
handler(val) {
console.log("第一次执行了", val);
this.fullName = val + "·" + this.lastName;
},
immediate: true, //在watch中声明后立即执行handler
},
},
watch的deep属性
vue无法检测到对象属性的添加或者删除,加上deep则可以检测。使用deep属性会给每一层都加上监听器,性能开销非常大,不建议使用,可以使用字符串监听。
data() {
return {
item: {
a: "",
b: "",
},
}
},
watch: {
// 加上deep,性能开销大
item: {
handler(val) {
console.log("item.a changed", val);
},
immediate: true,
deep: true,
},
// 不用deep,使用字符串监听
"item.a": {
handler(val) {
console.log("item.a changed", val);
},
immediate: true,
},
},
2.computed计算属性
依赖于其他数值变化,有缓存,只有其他数值发生变化才会调用,不需要在data()先定义,默认只有get,也可以使用set。
执行顺序:created-computed-mounted。
computed: {
// fullName: function () {
// return this.firstName + " " + this.lastName;
//},
fullName: {
// getter
get() {
console.log("computed");
return this.firstName + " " + this.lastName;
},
// setter
set(newValue) {
const names = newValue.split(" ");
this.firstName = names[0];
this.lastName = names[names.length - 1];
},
},
},
3.methods方法
只要调用就会重新执行一次。