vue 获取跳转上一页组件信息

项目中有一需求,需要根据不同的页面路径url跳转进行不同的操作,首先需要获得上一页面的url,利用 beforeRouteEnter 这个钩子中的from参数获得之前url的信息,然后给 next 传递回调来访问当前组件的实例。 

操作代码为:

beforeRouteEnter (to, from, next) {
       console.log(to)
       console.log(from)
 if (from.name === null) {
     //判断是否登录
    this.isYJLogin()
  }

},
methods: {
 isYJLogin(){
    localStorage.setItem('account', this.code)
  }
}

 如下图所示:

根据打印,也可以用这个name来判断,但是却报个错误:

查看代码,写法没有错误啊,最终查看官方文档,发现官方文档中也有说明:

beforeRouteEnter 守卫不能访问 this,因为守卫在导航确认前被调用,因此即将登场的新组件还没被创建。

可以这样更该下代码如图:

data(){
     return {
       newPath:''
     }
   },
   beforeRouteEnter(to, from, next){
     next(vm => {
       // 通过 `vm` 访问组件实例,将值传入newPath
        vm.newPath = from.name
       if (from.name === null) {
         //判断是否登录
          vm.isYJLogin()
        }
     })
},
methods: {
 isYJLogin(){
    localStorage.setItem('account', this.code)
  }
}

注:beforeRouteEnter这个方法在mounted:function()之后运行。

猜你喜欢

转载自blog.csdn.net/dt1991524/article/details/84589779