标签:VUE vocabulary next 路由 跳转 router fullPath store
需求:用户编辑后,若池中有数据,则在离开页面时提示保存。
由于一个页面不单会有返回,还会有其他各个页面的导航,导致单把逻辑写在返回按钮中无法实现需求。路由导航可以做到:
官方文档
参考
router.beforeEach((to, from, next) => {
console.log(to); // 即将要进入路由的对象
console.log(from); // 当前导航要离开的路由对象
console.log(next); // 调用next该方法,才能进入下一个路由
next();
});
实例代码:router根文件
import {MessageBox} from 'element-ui'
import store from '../store/index'
import Router from 'vue-router'
//..............
const router = new Router({......})
//..............
router.beforeEach((to, from, next) => {
let fromPath = from.fullPath==='/vocabulary/create'||from.fullPath==='/vocabulary/edit'
let toPath = to.fullPath!='/vocabulary/create'&&to.fullPath!='/vocabulary/edit'
let editTF = store.state.vocabulary.checkedList.length;
// 来自这俩路由 去的不是这俩路由 且有编辑内容
if(editTF&&fromPath&&toPath){
MessageBox.confirm('您有编辑内容尚未保存,确认退出?', '提示', {
confirmButtonText: '确定',
type: 'warning',
center: true,
}).then(() => {
store.commit(`vocabulary/coverCheckedList`,[]);
next();
}).catch(() => {
// // next(false);
// // router.replace(to.fullPath);
// // router.push(to.fullPath)
// // next(from.fullPath);
// // abort();
// router.back();
});
} else {
store.commit(`vocabulary/setSearchModel`,{});
store.commit(`vocabulary/setSearchModel_Page`,{});
store.commit(`vocabulary/setCurTab`,true);
next();
}
})
但由于我需求具有一定特殊性,这样会导致用户点击取消进入死循环,试了很多方法都不行。
于是另辟蹊径,找到VUE的生命周期:beforeRouteLeave
beforeRouteLeave(to,from,next){
let fromPath = from.fullPath==='/vocabulary/create'||from.fullPath==='/vocabulary/edit'
let toPath = to.fullPath!='/vocabulary/create'&&to.fullPath!='/vocabulary/edit'
let editTF = this.$store.state.vocabulary.checkedList.length;
// 来自这俩路由 去的不是这俩路由 且有编辑内容
if(editTF&&fromPath&&toPath){
this.$confirm('您有编辑内容尚未保存,确认退出?', '提示', {
confirmButtonText: '确定',
type: 'warning',
center: true,
}).then(() => {
this.$store.commit(`vocabulary/coverCheckedList`,[]);
next();
}).catch(() => {
return
});
} else {
this.$store.commit(`vocabulary/setSearchModel`,{});
this.$store.commit(`vocabulary/setSearchModel_Page`,{});
this.$store.commit(`vocabulary/setCurTab`,true);
next();
}
}
完美解决需求~
标签:VUE,vocabulary,next,路由,跳转,router,fullPath,store 来源: https://blog.csdn.net/Beatingworldline/article/details/120717962
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。