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

Viewed 1709

I have encountered a problem with Vue router recently, imagine that we have a Vue CLI project and our App component is like below:

<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>

Our one and two components are:

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

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

and

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

and our router file is:

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
        }
    ]
});

The problem is, when I open the page for the first time, everything is fine and the second component recognizes the prop and shows "two, the message is hello". the router links all work fine when I click on them and the prop is passed properly. The problem appears when I refresh the page, and it only shows "two, the message is".

What I have done to solve this: It seems that this.$router.push is not working correctly after the second page refresh, and the reason is the duplicated navigation error which doesn't let you navigate to the same route.

The questions are:

  1. Did I recognize the problem correctly? Is it because of the duplicated navigation?
  2. If that's the problem, how can I make a router component to always mount on the page refresh, with the prop passed to it properly?
1 Answers

Route params that are not included in the path (eg /route/:param) do not persist on page reload. They live only in-memory for the current session.

What I would do instead is

  1. Remove the created hook in your App component

  2. Set up a redirect from / to two in your router

    {
      path: "/",
      redirect: { name: "two", params: { message: "hello" } }
    }
    
  3. Set a default value for the prop in two to handle reloads

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