Enter the details page from the list and carry parameters. In order to keep the list page at a fixed position, a package is used. In keep-alive
this case, you need to watch
listen to the route to obtain parameters when entering the details page.
watch: {
$route: {
handler() {
// do some thing
},
immediate: true // 立即监听
}
}
However, there is a problem,
because the current route is monitored, and
it will also be triggered when returning to the previous page watch
.
At this time, parameters will be lost,
which may cause business logic errors.
My first reaction is handler
to make judgments in the function body and
not execute the corresponding code.
After one operation, the goal is achieved,
but watch
it will still be triggered.
As a moral programmer,
this is not allowed,
so I thought about how to remove it . watch
Just like document.removeListenr
this, arrange! ! !
data() {
return {
watchRoute: () => {}
}
}
// 定义监听函数
created() {
this.watchRoute = this.$watch(
// 此处被监听的对象必须是一个函数,否则会报错
() => {
return this.$route
},
() => {
// do some thing
}, { immediate: true })
}
destroyed() {
// 页面销毁时调用监听函数,就可以移除watch
this.watchRoute()
}
Insert another knowledge point here : keep-alive
the component will not be executed destroyed
, and created
the function will only be executed once.
To be replaced by activated
(activation) and deactivated
(deactivation) functions respectively.