Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue-router component reusing

I would like to know how can I stop component reusing in Vue-router.

I'm building a simple page application and I am unable to update data after clicking the same link twice.

Is it possible to somehow force reloading or what are the best practices in my situation?

like image 863
user8540556 Avatar asked Sep 25 '18 19:09

user8540556


People also ask

How do you reuse Vue components?

Component Registration Each component you create in your Vue app should be registered so Vue knows where to locate its implementation when it is encountered in a template. To register your component in another component, you should add it to the components property in the Vue object.

Does Vue have reusable components?

Create reusable components in VueWe will learn to build a reusable component in Vue, which will be used to reuse it in Create or Edit or anywhere that requires the same code and functionality. Reusing a component or code helps us avoid writing the same code and functionality multiple times.

Should you use history mode for Vue router?

The default mode for vue-router is hash mode - it uses the URL hash to simulate a full URL so that the page won't be reloaded when the URL changes. To get rid of the hash, we can use the router's history mode, which leverages the history.


2 Answers

Vue Router reuses the same component therefore the mounted hook won't be called. As stated in the documentation:

The same component instance will be reused [...] the lifecycle hooks of the component will not be called.

If you want to update the data you have two options:

  • Watch the $route object

const User = {
  template: '...',
  watch: {
    '$route' (to, from) {
      // react to route changes...
    }
  }
}
  • Use the beforeRouteUpdate navigation guard

const User = {
  template: '...',
  beforeRouteUpdate (to, from, next) {
    // react to route changes...
    // don't forget to call next()
  }
}

For a more detailed explanation you can check the section Reacting to Param Changes of the Vue Router documentation: https://router.vuejs.org/guide/essentials/dynamic-matching.html#reacting-to-params-changes.

like image 73
pedfercue Avatar answered Oct 10 '22 01:10

pedfercue


Use the key attribute on router-view set to current url. It's built in, so no need to write any code.

<router-view :key="$route.fullPath"></router-view>
like image 27
Mariusz Jamro Avatar answered Oct 10 '22 02:10

Mariusz Jamro