'Vue js rerender the same component when changing route
I have one auth component that I am using both in the login and the signup route.
const routes = [{
path : '/',
name: 'home',
component: Home
}, {
path : '/signin',
name: 'signin',
component: Auth
},
{
path : '/signup',
name: 'signup',
component: Auth
}];
If for example, I'm on the login page The problem is if I type something in the text inputs and go to the signup the text is still there, how I force the component to reinitialize?
Solution 1:[1]
You can use the key attribute to indicate vue to rerender some elements instead of reusing them.
e.g. you have an <input/> in your Auth component which you want to rerender under different routes, add a key data prop to Auth, use <input :key="key"/> in the template. In your case here,
data() {
key: this.$route.path
}
may be a good choice.
Solution 2:[2]
vuejs caches rendered component. you don't provide Auth component code, but i think the following helps you.
<template>
<input type="text" ID="username" v-model="usernameinput">
<!-- other text boxes and inputs -->
</template>
export default {
name: 'Auth',
//component code .....
data: function() {
return {
usernameinput: '',
//and other stuff
}
},
watch: {
// call method if the route changes
'$route': 'reInitialize'
},
methods: {
reInitialize: function() {
this.usernameinput = '';
//and so on
}
},
//remainig component code
}
also there is another posibilty, may be you are using dynamic components and keep-alive is true.
Solution 3:[3]
You should watch route params and when it changes, re-execute to fetch data. Example
created() {
// watch the params of the route to fetch the data again
this.$watch(
() => this.$route.params,
() => {
this.fetchData()
},
// fetch the data when the view is created and the data is
// already being observed
{ immediate: true }
)
},
More info at https://router.vuejs.org/guide/advanced/data-fetching.html#fetching-after-navigation
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JJPandari |
| Solution 2 | |
| Solution 3 | Alberto Arzuaga Torres |
