Vuejs中的页面刷新后,没有将Prop传递给路由器组件



我最近遇到了Vue路由器的问题,假设我们有一个Vue CLI项目,我们的应用程序组件如下所示:

<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. 如果这是问题所在,我如何使路由器组件始终安装在页面刷新上,并将道具正确传递给它

路径中未包含的路由参数(例如/route/:param(在页面重新加载时不会持久存在。它们只存在于当前会话的记忆中。

我会做的是

  1. 移除App组件中的created挂钩

  2. 在路由器中设置从/两个的重定向

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

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

最新更新