vue中实现页面的拦截、跳转、判断

1,全局前置守卫:beforeEach

const router =new Router({……});
router.beforeEach((to, from, next) => {
 
});

2,全局后置守卫:afterEach

3,路由独享的钩子函数(路由守卫):beforeEnter

在配置路由的时候直接定义beforeEnter守卫,跳转到这个路由时候才会执行
const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      }
    }
  ]

4 组件内的钩子函数(组件守卫)
直接写在单个vue文件中的中,写的位置跟mounted之类的钩子函数同级别。参数都是to、from、next

4.1 beforeRouteEnter
作用:在渲染该组件对应的路由被confirm前调用,

注意:这时候该组件的this不能使用,因为组件实例还没被创建。

4.2 beforeRouteUpdate
作用:当前路由改变,但是该组件被复用时候调用,举例来说,对于三级导航,一个带有动态参数的路径/index/id,在/index/1和 /index/2之间跳转的时候,由于会渲染同样的index组件,因此该组件会被复用,而这个钩子会就再复用的时候调用。

注意:可以使用组件的实力this

4.3 beforeRouteLeave
作用:导航离开该组件对应的路由时调用

5,单个vue文件中,设置监听

 watch: {
        $route: {
            handler: function(val, oldVal){
                if(oldVal.path== "/map"){
                // this.$refs.tclb.closeDrawer()
                this.drawer=false;
                }
                if(val.path== "/map"){
                    document.getElementById("tclb_container").style.display="block";
                     this.getParams();
                //this.drawer=false;
                }
                
            },
            
            // 深度观察监听
            // deep: true
        },
       // "$route":"getPath" // 监听事件
  },
原文地址:https://www.cnblogs.com/shuihanxiao/p/15302759.html