【问题标题】:Prop is not being passed to router component after page refresh in Vuejs在 Vuejs 中刷新页面后,Prop 未传递给路由器组件
【发布时间】:2021-01-29 14:52:26
【问题描述】:

我最近遇到一个Vue路由器的问题,假设我们有一个Vue CLI项目,我们的App组件如下:

<template>
  <div id="app">
    <div class="links">
      <router-link to="one">one</router-link>
      <router-link to="two">two</router-link>
    </div>
    <div class="routers">
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
export default {
  data: function(){
    return{

    }
  },
  created(){
    this.$router.push({
      name: 'two',
      params:{
        message: 'hello'
      }
    });
  }
}
</script>

我们的一个和两个组件是:

<template>
    <div>
        two, the message is {{ message }}
    </div>
</template>

<script>
export default {
    props:[
        "message"
    ]
}
</script>

<template>
    <div>
        one
    </div>
</template>

我们的路由器文件是:

import Vue from 'vue'
import VueRouter from 'vue-router'
import one from '../components/one.vue'
import two from '../components/two.vue'

Vue.use(VueRouter);

export const router = new VueRouter({
    routes:[
        {
            path: '/one',
            name: 'one',
            component: one
        },
        {
            path: '/two',
            name: 'two',
            component: two,
            props: true
        }
    ]
});

问题是,当我第一次打开页面时,一切都很好,第二个组件识别出道具并显示“二,消息是你好”。当我单击它们并且正确传递了道具时,路由器链接一切正常。 刷新页面时出现问题,只显示“二,消息是”。

我做了什么来解决这个问题:似乎this.$router.push 在第二次页面刷新后无法正常工作,原因是重复的导航错误无法导航到同一条路线。

问题是:

  1. 我是否正确识别了问题?是因为重复导航吗?
  2. 如果这是问题所在,我怎样才能使路由器组件始终挂载在页面刷新时,并正确传递给它的道具?

【问题讨论】:

标签: vue.js vue-component vue-router


【解决方案1】:

不包含在路径中的路由参数(例如/route/:param)不会在页面重新加载时保留。它们只存在于当前会话的内存中。

我会做的是

  1. 删除 App 组件中的 created 钩子

  2. 在您的路由器中设置一个从/两个redirect

    {
      path: "/",
      redirect: { name: "two", params: { message: "hello" } }
    }
    
  3. two 中的 prop 设置默认值以处理重新加载

    props: {
      message: {
        type: String,
        default: "hello"
      }
    }
    

【讨论】:

  • 感谢您的帮助,此解决方案完美运行!
猜你喜欢
  • 1970-01-01
  • 2020-05-22
  • 1970-01-01
  • 1970-01-01
  • 2018-08-17
  • 1970-01-01
  • 1970-01-01
  • 2020-10-09
  • 2019-05-15
相关资源
最近更新 更多