[Vuejs]-Vue router dynamic link and children reload page – not load correctly component

0👍

Problem:

From the Vue.JS website: "Vue does provide a more generic way to observe and react to data changes on a Vue instance: watch properties." When you refresh the page the watch() method will not be executed because it is a new Vue instance and no data has changed on the Vue instance yet. You should probably use a different pattern to determine which component to show. (https://v2.vuejs.org/v2/guide/computed.html#Computed-vs-Watched-Property)

Solution:

I suggest making the EditWarehouse a sibling route to ShowWarehouse, and make EditWarehouse its own component (you already have this). Your router-link in the ShowWarehouse component can stay the same.

Code Snippet:

const ShowWarehouse = {
  template: `<div><h1>ShowWarehouse</h1> <div v-if="warehouseData">
    <div>Name: {{ warehouseData.warehouse.name }}</div>
    <div>ID: {{ $route.params.id }}</div>
    <div>
      <router-link :to="{ name: 'EditWarehouse'}">Edit</router-link>
    </div>
  </div></div>`,
  computed: {
    warehouseData: function() {
      let data;

      let id = this.$route.params.id;
      if (id) {
        data = {
          warehouse: {
            name: 'Some Warehouse Name',
            id: id
          }
        }
      }

      return data;
    }
  }
};

const EditWarehouse = {
  template: "<h1>EditWarehouse [{{ $route.params.id }}]</h1>"
}

const router = new VueRouter({
  routes: [{
      path: '/warehouse/:id',
      name: 'ShowWarehouse',
      component: ShowWarehouse
    },
    {
      path: '/warehouse/:id/edit',
      name: 'EditWarehouse',
      component: EditWarehouse
    }
  ]
});


new Vue({
  el: '#app',
  router
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app">
  <p>
    <router-link :to="{ name: 'ShowWarehouse', params: { id: 123 }}">Go to Warehouse 123</router-link>
  </p>
  <router-view/>
</div>

Here is a jsfiddle with the same code:
https://jsfiddle.net/austinwasinger/oruswb3a/39/

Leave a comment