When navigating in my Vue application, I utilize vue-router's beforeRouteEnter and beforeRouteUpdate to retrieve data from a REST API.
<template>
<div>
<h2>{{ league.name }} </h2>
<user-list :users="league.leaderboard" type="list"/>
</div>
</template>
<script>
import UserList from '../components/UserList.vue'
import League from '../model/League'
export default {
components: {
UserList
},
data() {
return {
league: { name: 'init', leaderboard: [] },
}
},
methods: {
setLeague(league) {
this.league = league
}
},
beforeRouteEnter(to, from, next) {
League.$find(to.params.league)
.then(league => {
next(vm => {
vm.league = league
})
})
.catch(err => {
if(err.response && err.response.status == 404)
next('/404')
else
next(vm => vm.error = err)
})
},
watch: {
league() {
console.log('league changed ', this.league)
}
},
beforeRouteUpdate(to, from, next) {
this.league = null
League.$find(to.params.league)
.then(league => {
this.setLeague(league)
console.log('beforeUpdate: ', this.league)
next()
})
.catch(err => {
if(err.response && err.response.status == 404)
next('/404')
else {
this.error = err
next()
}
})
}
}
</script>
<style>
</style>
the beforeRouteEnter guard works as expected.
In my application, there's a situation where the route changes from /leagues/1
to /leagues/1
, causing the component to be reused and triggering the beforeRouteUpdate guard. Despite successfully fetching new data, when calling next(), the `this.league` data reverts back to the initial value (name: 'init' etc.) defined in the data function. The reason behind this behavior remains unclear.
This code was adapted following the vue docs instructions here.
An interesting observation is that setting `this.league = null` triggers the watcher, while `this.setLeague` does not. Additionally, the output logged in beforeUpdateRoute is not a vue observer but the plain league object itself. Attempts to modify the `this.setLeague` call did not resolve the issue.