Reputation: 9474
I have built a profile vue page but I realized that when I change URL parameter it does not load new user but displays the first user. I load data in created
which is probably the cause. How can I tell the page that it has a different parameter and it shall reload?
router.js
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/profile/:id',
name: 'user-profile',
component: () => import('./views/Profile.vue'),
props: true,
},
Profile.vue
async created() {
const response = await this.$store.dispatch('GET_USER_PROFILE_BY_ID', { id: this.id });
this.userProfile = response.data.data;
URLs:
Upvotes: 0
Views: 403
Reputation: 4930
The created hook only gets executed when the component is actually created. changing the url to load the same route, but with a different ID is a routeUpdate instead.
Remember that params or query changes won't trigger enter/leave navigation guards. You can either watch the $route object to react to those changes, or use the beforeRouteUpdate in-component guard.
https://router.vuejs.org/guide/advanced/navigation-guards.html
Abstract out the fetch & set that you have in your created hook. Then, call it in both created() and beforeRouteUpdate().
{
methods: {
async getProfile(id) {
const response = await this.$store.dispatch('GET_USER_PROFILE_BY_ID', { id});
this.userProfile = response.data.data;
}
created() { this.getProfile(this.id); },
beforeRouteUpdate(to, from, next) {
const { params: {id} } = to;
this.getProfile(id);
next();
}
}
Upvotes: 2