假设有这样一个需求,用户在一个页面内编辑文字,但是并未点击保存并且跳转到了下一个路由。比较好的做法应该是给出一个提示—“您编辑的内容还未保存,是否确认退出?”用户如果点击“确定”,那么不保存当前内容直接退出,用户如果点击“取消”,则取消本次路由跳转,继续留在原来的页面。
尝试的错误做法
一开始的时候我是想着使用vuex结合vue router的beforeEach导航守卫来实现。
首先在vuex中新增一个状态值—introduceState
const store = new Vuex.Store({
strict: true, // process.env.NODE_ENV !== 'production', 直接修改state 抛出异常
state: {
....
introduceState: false,
....
},
getters: {
introduceState: state => state.currentMenus
},
mutations: {
// 更新introduceState的值
changeIntroduceState (state, value) {
state.introduceState = value
}
}
})用户在点击跳转到另一个页面的时候会触发生命周期函数beforeDestroy,在这个函数中我们可以检测用户的编辑内容是否保存,如果尚未保存。
如果内容尚未保存,我们就弹出一个提示框,当用户选择取消的时候,就将vuex中的introduceState值更新为true。
</script>
import { mapGetters, mapActions, mapMutations } from "vuex"
export default {
data() {
return {
contentHasSave: false // 记录用户是否已经保存内容
}
},
methods: {
...mapMutations({
changeIntroduceState: changeIntroduceState
})
},
beforeDestory: function(){
if(!contentHasSave){
// 使用element的提示框
this.$confirm('您还未保存简介,确定需要提出吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
// 选择确定,正常跳转
})
.catch(() => {
// 选择取消
this.changeIntroduceState(true)
})
}
}
}
</script>
最后在router的beforeEach的导航守卫里监测from为当前页面的所有路由跳转。当state的introduceState为true的时候使用next(false)来取消本次路由跳转
import Vue from "vue";
import VueRouter from "vue-router";
import routeConfig from "./routes";
import {sync} from "vuex-router-sync";
import store from "../store";
//加载路由中间件
Vue.use(VueRouter)
//定义路由
const router = new VueRouter({
routes: routeConfig,
//mode: 'history'
})
sync(store, router)
router.beforeEach((to, from, next) => {
// 简介也未提交,取消跳转










