Reputation: 1219
I'm using vue-router and trying to link from one user record to another, pretty simple.
My route is boilerplate from vue-router docs:
{ path: '/user/:user_id', name: 'user', component: User, props: true },
I'm linking with the following code:
<a @click="selectUser(user.parent)">{{user.parent.email}}</a>
The method:
selectUser(user) {
this.$router.push({ name: 'user', params: { user_id: user.id } })
},
I'm attempting to use beforeRouteUpdate to load up the changed user:
beforeRouteUpdate (to, from, next) {
alert(this.user_id)
this.fetch()
next()
},
And my fetch method:
fetch() {
this.$store.dispatch('users/fetchUser', this.user_id)
},
I'm using vuex as well. The alert of the this.user_id (prop) in the beforeRouteUpdate responds with the original id, not the changed one. Shouldn't it be the newly changed/passed ID? The url changes to the new id, but it simply loads data with the old/original ID rather than the newly passed one.
Upvotes: 3
Views: 2679
Reputation: 197
Another way is to use a watch on the prop user_id
, when it changed you can execute the method fetch()
In your case:
watch: {
user_id: function(newVal, oldVal) {
this.fetch();
}
},
I hope this can be a useful!
Upvotes: 1
Reputation: 4149
You need to use to.params
to access route params. You need to assign values on your component. They don't get assigned automatically.
In your case, you need to assign to.params.user_id
to this.user_id
before calling this.fetch()
in beforeRouteUpdate
.
beforeRouteUpdate (to, from, next) {
this.user_id = to.params.user_id
alert(this.user_id)
this.fetch()
next()
}
Refer to docs about in-component navigation guards.
Upvotes: 3