比如平時created時要請求一次數(shù)據(jù)宪躯,并且當搜索值改變罐旗,也要請求數(shù)據(jù)膳汪,我們會這么寫
created(){
this.getList()
},
watch: {
searchInputValue(){
this.getList()
}
}
使用immediate完全可以這么寫,當它為true時九秀,會初始執(zhí)行一次(immediate為true的時候就會立即執(zhí)行handler函數(shù)遗嗽,默認是為false不執(zhí)行)
watch: {
searchInputValue:{
handler: 'getList',
immediate: true
}
}
下面代碼是,params發(fā)生改變就重新請求數(shù)據(jù)鼓蜒,無論是a痹换,b,c都弹,d屬性改變
data() {
return {
params: {
a: 1,
b: 2,
c: 3,
d: 4
},
};
},
watch: {
params: {
deep: true,
handler() {
this.getList;
},
},
}
但是如果我只想要a娇豫,b改變時重新請求,c畅厢,d改變時不重新請求呢锤躁?
mounted() {
Object.keys(this.params)
.filter((_) => !["c", "d"].includes(_)) // 排除對c,d屬性的監(jiān)聽
.forEach((_) => {
this.$watch((vm) => vm.params[_], handler, {
deep: true,
});
});
},
data() {
return {
params: {
a: 1,
b: 2,
c: 3,
d: 4
},
};
},
watch: {
params: {
deep: true,
handler() {
this.getList;
},
},
}