簡體   English   中英

在 Vuejs 中刷新頁面后,Prop 未傳遞給路由器組件

[英]Prop is not being passed to router component after page refresh in Vuejs

我最近遇到了 Vue router 的問題,假設我們有一個 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. 如果這是問題所在,如何使路由器組件始終安裝在頁面刷新上,並正確傳遞給它的道具?

路徑中未包含的路由參數(例如/route/:param )不會在頁面重新加載時保留。 它們只存在於當前會話的內存中。

我會做的是

  1. 刪除App組件中created鈎子

  2. 在路由器中設置從/兩個重定向

    { path: "/", redirect: { name: "two", params: { message: "hello" } } }
  3. 將 prop 的默認值設置為two以處理重新加載

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM