【问题标题】:How can I transmit from a component to another when redirecting in VueJS?在 VueJS 中重定向时如何从一个组件传输到另一个组件?
【发布时间】:2018-09-09 23:33:23
【问题描述】:

我目前正在制作一个登录表单,该表单将在用户连接后将其重定向到“/admin”。但是,如果他在未登录时尝试键入“/admin”,他将被重定向到“/login”。

我想要的是能够显示他为什么在这里的消息(例如“您必须连接才能继续”)。我也想在他连接时输入“/ login”时做同样的事情(在这种情况下,他将被重定向并显示“你已经登录”的消息)

我尝试以不同的方式传递数据,但不知何故,我无法检索它,我很确定那是因为我的方式不对。

这是“/admin”vue 布局,确保用户不断登录。

beforeCreate () {
    this.$axios.get('/logged_in')
      .then(response => {
        if (!response.data) { // either returns true or false
          this.$router.replace({ name: 'login', params: { error: 'not_logged' } })
        }
      })
  }

这是登录表单,以及“我如何”尝试检索参数的内容

created () {
    this.$axios.get('/logged_in')
      .then(response => {
        if (response.data) {
          this.$router.replace({ name: 'admin', params: { error: 'already_loggedin' } })
        }
      })
    console.log(this.$router.params)
  }
}

watch: {
  $route (to, from) {
    console.log(to)
    console.log(from)
  }
}

在 3 个console.logs 中,只有第一个 (this.$router.params) 实际显示在控制台中,undefined

我该怎么办?

提前谢谢你

【问题讨论】:

    标签: session redirect vue.js vue-router


    【解决方案1】:

    在 3 个 console.logs 中,只有第一个 (this.$router.params) 实际显示

    这很可能是因为您的组件在路由更改后已卸载。这就是观察者不再工作的原因。

    关于第一个console.log,如果你从第一个组件重定向到这里:

    this.$router.replace({ name: 'login', params: { error: 'not_logged' } })
    

    那我觉得 $route.params 应该有这个参数(不是 $router.params)。

    您还可以在组件上声明道具并从路由定义中传递它们,如下所述:https://router.vuejs.org/guide/essentials/passing-props.html#boolean-mode

    注意:

    当 props 设置为 true 时,route.params 将被设置为组件的 props。

    【讨论】:

      猜你喜欢
      • 2020-05-08
      • 2021-12-09
      • 2021-12-30
      • 2018-03-07
      • 2019-12-26
      • 2019-06-12
      • 2021-08-05
      • 2022-08-14
      • 2020-05-06
      相关资源
      最近更新 更多