VueJS: How to fix the Vue Router props-passing regression effect
See the documentation on GitHub at vuejs/vue-router for these solutions.
Description
vue-router causes the Vue object to not refresh props when navigating from component to component where a prop is needed to change something. This effect is referred to as "props-passing-regression". For example, this component requires that a prop called id to be passed in:
<script>
export default {
data() {
return {
id: this.$route.params.id
}
}
}
</script>
If you navigate to that component using the standard vue-router method, the data will NOT update after first visited if, for example the data changes. For example going from http://localhost:8000/user/1 to http://localhost:8000/user/2. Obviously this is a very common occurance.
There are different ways to solve this.
Solution 1: Extract route params at definition
Wherever you're defining the routes, add props: true to the route that takes parameters, example:
export const routes = [
{ path: '/user/:id', component: User, props: true },
];
You can process it with a custom function wherever you're setting the routes as well:
const fnSetId = route => {
return {
id: route.params.id
};
}
export const routes = [
{ path: '/user/:id', component: User, props: fnSetId }
];
Or if you want to sabotage the route, you can just pass a static value:
export const routes = [
{ path: '/user/:id', component: User, props: { id: 0 } }
];
For the working code example, see the VueJS documentation.
Solution 2: Using a watch
This is the old solution (pre v2.2) and not the best to use. Watch for route changes and execute from there given the route coming from (from) and going to (to).
<script>
export default {
data() {
return {
id: this.$route.params.id
}
},
watch: {
'$route'(to, from) {
this.id = to.params.id;
}
}
}
</script>