In my application some routes are just accessible for authenticated users.
When a unauthenticated user clicks on a link, for which he has to be signed in, he will be redirected to the login component.

If the user logs in successfully, I would like to redirect him to the URL he requested before he had to log in. However, there also should be a default route, in case the user did not request another URL before he logged in.

How can I achieve this using vue-router?


My code without redirect after login
router.beforeEach(
    (to, from, next) => {
        if(to.matched.some(record => record.meta.forVisitors)) {
            next()
        } else if(to.matched.some(record => record.meta.forAuth)) {
            if(!Vue.auth.isAuthenticated()) {
                next({
                    path: '/login'
                    // Redirect to original path if specified
                })
            } else {
                next()
            }
        } else {
            next()
        }
    }        
)



My login function in my login component

login() {
    var data = {
        client_id: 2,
        client_secret: '**************',
        grant_type: 'password',
        username: this.email,
        password: this.password
    }
    // send data
    this.$http.post('oauth/token', data)
         .then(response => {
             // authenticate the user
             this.$auth.setToken(response.body.access_token,
             response.body.expires_in + Date.now())
             // redirect to route after successful login
             this.$router.push('/')
          })
}

推荐答案

这可以通过将redirect path作为query parameter添加到路由中来实现.

然后在登录时,必须判断是否设置了重定向参数:

  • 如果设置为IS,则重定向到param中找到的路径
  • 如果设置为NOT,则可以使用root

Put an action to your link for example:

onLinkClicked() {
    if(!isAuthenticated) {
        // If not authenticated, add a path where to redirect after login.
        this.$router.push({ name: 'login', query: { redirect: '/path' } });
    }
}

The login submit action:

submitForm() {
    AuthService.login(this.credentials)
        .then(() => this.$router.push(this.$route.query.redirect || '/'))
        .catch(error => { /*handle errors*/ })
}

Vue.js相关问答推荐

如何根据数据库中的条件在vue中创建类

在Nuxt项目中混合Scrolltrigger与Lenis

如何用其他组件编译Vue模板?

Vue.js 3 没有组件的实例?

如何容器化 Vue.js 应用程序?

VueJS中的绑定函数含义

使用数组元素的计算(computed)属性

VueJS 插件的如何react式绑定?

ECMA6 中 nameFunction() {} 和 nameFunction () => {} 的区别

单击复选框后,V-model 未更新

Vuetify 单选按钮未显示为选中状态

从 Url 中删除查询字符串参数

错误:[vuex] 期望字符串作为类型,但发现未定义

在 Vue.js 中,为什么我们必须在导入组件后导出它们?

我可以修改 Vue.js VNodes 吗?

Select 下拉列表中的复选框后如何清除 v-autocomplete(多个)搜索输入?

VueJS 2 在多个组件上debounce

如何在 VueJS 中下载本地存储的文件

升级到 vue-cli 3 后,HTML 中的空格消失了

在 vue js 中的何处以及如何存储 API 端点?