Vue 如何实现登录后,跳转到登录之前要访问的页面

一、需求

有些时候,需要实现这样的功能:

  1. 项目中的有些页面是可以直接访问的,不需要登录。
  2. 但这个页面中的一些链接一些路径则需要登录后才能查看,也就是说点击这些链接的时候就直接跳转到登录页面了
  3. 在登录之后,需要重新定位到之前要访问的路径上去,而不是跳转到登录后的默认路径中

举个例子说:

  1. login 成功后会自动跳转到 /index 页面
  2. /index 页面中有一个 /user/info 的快捷路径
  3. 未登录之前点击 /user/info 这个路径,会直接跳转至 /login 页面
  4. 此时需要实现这样的功能,在登录之后,再回到之前要访问的 /user/info 路径上去

二、实现思路

那么如何实现这个需求呢。
用 store 来实现

  1. store.state 中新建一个变量 lastVisitPath 记录进入登录页面之前要去的 path
  2. 登录成功之后,判断 lastVisitPath 这个变量是否有值,如果有,就跳到这个路径上去,并清空这个变量值

三、实现

在 router 的 beforeEach 方法中判断,在跳转至登录之前记录这个 lastVisitPath

// 引入 state 和 mutation
computed: {
    ...mapState(['lastVisitRoute'])
},
methods: {
    ...mapMutations(['SET_LAST_VISIT_ROUTE']),
}

// 
if (token) {

} else {
    store.commit('SET_LAST_VISIT_ROUTE', to.path)
    next({path: '/login'})
}

登录成功后,如果存在 lastVisitPath 就跳转到它

// 引入 state 和 mutation
computed: {
    ...mapState(['lastVisitRoute'])
},
methods: {
    ...mapMutations(['SET_LAST_VISIT_ROUTE']),
}

// 
if (this.lastVisitRoute){
    this.$router.push({path: this.lastVisitRoute})
        .then(res => {
      		// 跳转成功后,清除这个 lastVisitRoute 变量值
            this.SET_LAST_VISIT_ROUTE(null)
        })
        .catch(error => {
            console.log(error)
        });
} else {
    this.$router.push({path: '/'}).catch(error => {
        console.log(error)
    })
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐