在Vuejs中刷新页面后,道具未传递到路由器组件

时间:2020-10-15 06:44:35

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

我最近遇到了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. 如果这是问题,我如何才能使路由器组件始终正确地传递到prop,并始终将其安装在页面上?

1 个答案:

答案 0 :(得分:0)

未包含在路径中的路由参数(例如/route/:param)不会在页面重新加载时持续存在。他们仅在当前会话的内存中生活。

我要做的是

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

  2. 在路由器中从/到{em>两个设置一个redirect

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

    props: {
      message: {
        type: String,
        default: "hello"
      }
    }
    
相关问题