mounted() {
this.watch_WX_DialogVisible();
},
watch: {
'basicInfoData.salesPlatform'(val) {
this.detailBasicInfoForm[2][0].params.advanceLabel =
'店铺:' + val;
this.detailBasicInfoForm[2][0].params.advanceCascade.salesPlatform = val;
this.clearPrintTemplate();
if (val === 'ANNTO' && this.basicInfoData.platformCarrierCode === 'SF') {
this.initPrinter();
}
this.$set(this.detailBasicInfoForm[2][0].params, 'advanceNotSearch', val === 'WX');
},
},
methods: {
// 监听微信打印模板事件
watch_WX_DialogVisible() {
this.$watch(
function () {
return this.$refs.detailForm.$refs.advanceIns[1].$refs.advanceDialog.dialogVisible;
},
function (newval) {
if (newval && this.basicInfoData.salesPlatform === 'WX') {
this.$set(this.$refs.detailForm.$refs.advanceIns[1].$refs.advanceDialog.searchObj, 'keyword', this.basicInfoData.platformCarrierCode || '');
this.$refs.detailForm.$refs.advanceIns[1].$refs.advanceDialog.fetchData();
}
}
}
1.Vue 中,$watch 是一个用于深度观察一个对象或者一个 Vue 实例属性的方法。
一旦被观察的对象发生改变,就会触发一个回调函数。
2,关于为什么 watch_WX_DialogVisible方法没有写在 watch: 里,而是使用 $watch?
主要是因为 Vue 的 watch 选项有一个限制:它只能监听 Vue 实例的数据变化。然而,dialogVisible 并不是 Vue 实例的数据,而是引用了一个子组件的属性。如果不想修改公共组件,使用 $watch 可以解决。 过度使用 $watch 可能会导致性能问题,,在这种情况下,你可能需要考虑其他解决方案,比如使用计算属性或者只对特定的数据使用 $watch。
3,watch_WX_DialogVisible这方法使用了 $watch,作用是监听 dialogVisible 属性。当这属性变为 true,且 salesPlatform 为 WX 时,设置 searchObj.keyword 为 platformCarrierCode 的值。
<template>
<div>
<div>我是组件</div>
<el-button @click="dataArrAdd()">向数组中添加元素</el-button>
<div v-if="showMsg">添加成功</div>
</div>
</template>
<script>
export default {
data() {
return {
dataArr: [],
showMsg: false,
};
},
//watch: {
// dataArr:function(newval,old) {
// this.showMsg= !this.showMsg;
// },
},
created() {
let unDataArr = this.$watch(
() => {
return this.dataArr;
},
function(newval,old) {
this.showMsg= !this.showMsg;
unDataArr();
}
);
},
methods: {
dataArrAdd() {
this.dataArr.push("1");
},
},
};
1,调用unDataArr()在执行一次监听事件后就会移除监听
2,$watch中第一个参数是监听的对象,只要return的值发生变化,函数就会调用,第二个参数是function (newVal, oldVal) {}和watch的写法一样
3,$watch来监听之后来取消监听,不用占用性能