vue组建内部导航守卫 查询上个路由页面地址并赋值到本页面 监听用户未保存修改前突然离开

    技术2023-12-27  76

    导航守卫事件:

    首先大家都知道,官方文档所说:你可以在路由组件内直接定义以下路由导航守卫!于是我们在目标页面可以增加3个路由监听函数; beforeRouteEnter beforeRouteUpdate (2.2 新增) beforeRouteLeave

    beforeRouteEnter (to, from, next) { // 在渲染该组件的对应路由被 confirm 前调用 // 不!能!获取组件实例 `this` // 因为当守卫执行前,组件实例还没被创建 console.log(to) console.log(from) }, beforeRouteUpdate (to, from, next) { // 在当前路由改变,但是该组件被复用时调用 // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候, // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。 // 可以访问组件实例 `this` }, beforeRouteLeave (to, from, next) { // 导航离开该组件的对应路由时调用 // 可以访问组件实例 `this` }

    获取上个路由地址并赋值

    根据官方所说在beforeRouteEnter 事件中是不能调用this的,因为此时组件实例还没被创建,可以用vm来代替;如下

    data(){ return{ fromPath: '' } } beforeRouteEnter (to, from, next) { // 在渲染该组件的对应路由被 confirm 前调用 // 不!能!获取组件实例 `this` // 通过 `vm` 访问组件实例 // 因为当守卫执行前,组件实例还没被创建 console.log(to) console.log(from) next((vm)=>{ vm.fromPath = from.path }) },

    然而此时你在mounted中并不能打印到 this.fromPath赋值后的结果,找了很多文章都说在mounted中调用this. n e x t T i c k ( ) , 官 方 说 明 t h i s . nextTick(),官方说明this. nextTick()this.nextTick()是将回调延迟到下次 DOM 更新循环之后执行。在修改数据之后立即使用它,然后等待 DOM 更新。

    BUT!!!

    mounted中调用this.$nextTick()打印的结果表明无法获取赋值后的结果。因为beforeRouteEnter 中 next() 执行时机在组件mounted周期之后!!!! 于是我想到了watch来监听于是得到了我想要的结果

    watch(){ fromPath(newVal){ console.log("this.fromPath==="+this.newVal) } }

    此时,无论在mounted还是method中即可使用this.fromPath。

    监听用户未保存修改前突然离开

    这个离开守卫通常用来禁止用户在还未保存修改前突然离开。该导航可以通过 next(false) 来取消。

    beforeRouteLeave (to, from, next) { const answer = window.confirm('还有未保存的内容,确定要离开嘛?') if (answer) { next() } else { next(false) } }

    楼主也在不断学习中,如有写的不对的地方,欢迎大佬指导沟通!

    Processed: 0.017, SQL: 9