深度监听 watch
通常用于监听某个对象发生改变时,调用需要执行的方法,类似于js里面onchange或者addEventListener的作用。
之前遇到一个问题,公司的日期组件有个bug,把设定的显示值当作默认值,这样就算不操作,日期对象里也会有值,无法用是否为空来判断用户选择过。
于是我加了一个监听,用户进行选择会触发,改变标志位的值。
watch: {
startdate: {
handler: function (newValue) {
this.clickstartdate = true;
},
deep: true,
},
enddate: {
handler: function (newValue) {
this.clickenddate = true;
},
deep: true,
},
},
if (this.clickstartdate == false || this.clickenddate == false) {
this.errorMsg.content.push("日期不能为空");
}
这里必须要用deep进行深度监听,因为date是一个对象,改变的是里面的year month day属性,数组的变化则不需要。
有时也用于监听路由:
watch: {
'$route': 'getData',
},
另外可以用 immediate: true 实现在第一次绑定的时候也执行函数。
计算属性 computed
用于监听data中声明过或者父组件传递props中的数据,当发生变化时,触发其他操作。
如下实现全选/全不选功能,我在每列数据里加了ischecked属性,全选框增加allchecked属性:
//全选
handleAllcheck () {
if(this.allchecked) {
this.campdata.forEach((item) => {
item.ischecked = true;
this.chooseCampId(item.campid);
})
}else{
this.campdata.forEach((item) => {
item.ischecked = false;
this.chooseCampId(item.campid);
})
}
},
当发生选择/取消选择操作时,改变ischecked值会触发isAllChecked方法,返回是否全选,并用watch监听赋值给allchecked属性,这样当单个都选择后,全选框会打勾。
watch:{
isAllChecked () {
this.allchecked = this.isAllChecked;
}
},
computed: {
isAllChecked () {
let temp = true;
for(let i = 0; i < this.campdata.length; i ++) {
temp = temp && this.campdata[i].ischecked;
}
return temp;
}
},
注意是根据依赖关系进行缓存的计算,并且只在需要的时候进行更新,且不支持异步,当computed内有异步操作时无效,无法监听数据的变化。