1.编辑页代码(需要使用该功能的页面)
beforeUpdate() {
// 重置表单
const { useStaff, fuzzyKeywords, accurateKeywords, ruleForm, sceneList }=this.$options.data();
sceneList.push({ chatRoomList: [], tagList: [] });
const oldVal = { //存到变量oldVal(初始数据)中
useStaff,
fuzzyKeywords,
accurateKeywords,
sceneList:
this.labelType === AUTOLABEL_TYPE["intoGroup"]
? [{ chatRoomList: [], tagList: [] }]
: [
{
sceneType: NEWCUSOMTER_SCENE_TYPE["day"],
loopPoint: NEWCUSOMTER_SCENE_TYPE["day"],
},
],
...ruleForm,
};
const newVal = { //变量newVal(实时更改的数据)
useStaff: this.useStaff,
fuzzyKeywords: this.fuzzyKeywords,
accurateKeywords: this.accurateKeywords,
sceneList: this.sceneList,
...this.ruleForm,
};
checkChange(oldVal, newVal); // 调用的utils中的方法
},
2.utils中的checkChange方法(checkChange对应上图的checkChange,是从utils中导入的)
export const checkChange = (oldVal, newVal) => {
// 将新值与旧值进行对比并取反,存入sessionStorage的change中
window.sessionStorage.setItem('change', !isEqual(newVal, oldVal));
};
3.在main.js中设置路由导航守卫监听
router.beforeEach((to, from, next) => {
// 拦截需要提示的路由name,whitePathName:这里相当于一个白名单,用于判断哪些页面需要使用该功能
const whitePathName = ['CustomerOSP/addSOP',"AddRule"];
//所有的编辑页
if (from.path !== '/' && !whitePathName.includes(from.name)) {
// 设置编辑页从哪个路由跳转来,在返回的时候使用push
window.sessionStorage.setItem('from', from.path);
}
// 若当前是通过浏览器返回,则不进行拦截
if (window.history && window.history.pushState) {
let url = window.location.pathname + window.location.search
if (url !== from.fullPath) {
return next();
}
}
if (!whitePathName.includes(from.name)) return next();
if (window.sessionStorage.getItem('change') === 'true') {
Vue.prototype.$confirm('离开后,当前页面更改内容不会保存,是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
next();
window.sessionStorage.setItem('change', false);
}).catch(() => {
next(false);
});
} else {
next();
}
});