简述:vue 的watch的监听使用的几种写法。常用第4中写法。
一、$route监听路由跳转
前提:当需要前端监听路由跳转的时候,一般写在App.vue入口
//App.vue
//vue2、uniapp写法
watch: {
$route(to, from) {
if (hasPermission(to.path)) {
this.$store.commit("setIisShipGuid", false);
} else {
this.$store.commit("setIisShipGuid", true);
}
},
},
二、监听store中的某些变量
//vue2、uniapp写法
watch: {
"$store.state.isShipGuid": {
handler(newVal, oldVal) {
if (newVal !== oldVal) {
this.isShipGuid = newVal;
}
},
immediate: true,
deep: true,
},
},
//vue3 setup写法
watch(
() => store.selectShip.mmsi,
(oldNum, newNum) => {
if (oldNum != newNum) {
try {
cabin.getEngineRoomMenu(store.selectShip.mmsi);
} catch (error) {
cabin.getEngineRoomMenu(store.selectShip.mmsi);
}
}
},
{ immediate: true, deep: true }
);
三、自定义组件内部监听传参
//封装的一个图表组件。监听传参
//vue2、uniapp
export default {
props: {
height: {
type: String,
default: "100%",
},
width: {
type: String,
default: "100%",
},
echartsId: {
type: String,
required: true,
},
series: {
type: Array,
default: [],
},
title: {
type: Object,
default: null,
},
},
//监听传参
watch: {
myOption: function (newVal) {
if (newVal) {
console.log(
"=================================================================="
);
this.myCharts.clear();
this.init();
}
},
series: function (newVal) {
if (newVal) {
console.log(
"=================================================================="
);
this.myCharts.clear();
this.init();
}
},
},
}
//vue3写法
//监听多个参数的数组的写法
watch(
[() => props.modelValue, () => data.defaultFileList],
([newValue1, newValue2]) => {
console.log("newValue1", newValue1, "newValue2", newValue2);
},
{ deep: true }
);
四、监听单个页面组件内部的data()
(一)、监听某一个对象
data() {
return {
isActive: 0,
}}
//vue2、uniapp写法
//vue2在单个页面组件内部,只能有一个watch
//vue3在单个页面组件内部,可以有多个watch
watch: {
isActive(newval) {
this.currentIndex = newval;
},
"$store.state.mmsi": {
handler(newVal, oldVal) {
if (newVal !== oldVal) {
this.mmsi = newVal;
this.getEngineRoomMenu(this.mmsi);
}
},
immediate: true,
deep: true,
},
},
(二)、监听一个对象的某一个属性
//vue、uniapp写法
watch: {
'search.name': {
handler() {
// todo
},
}
}
或者:
computed: {
getName: function() {
return this.search.name
}
}
watch: {
getName: {
handler: function() {
//todo
},
}
}
const data = reactive({
ruleForm: {
param: {},
},
)
//vue3写法
watch(
() => data.ruleForm.param.publishType,
(newName, oldName) => {
if (newName === 1) {
data.useridsList_display = true;
} else if (newName === 0) {
data.ruleForm.param.useridsList = [];
data.useridsList_display = false;
}
},
{
immediate: true,
deep: true,
}
);
其它,