How does vue remove watch monitoring?

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-alivethis case, you need to watchlisten 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 handlerto make judgments in the function body and
not execute the corresponding code.
After one operation, the goal is achieved,
but watchit will still be triggered.
As a moral programmer,
this is not allowed,
so I thought about how to remove it . watch
Just like document.removeListenrthis, 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-alivethe component will not be executed destroyed, and createdthe function will only be executed once.
To be replaced by activated(activation) and deactivated(deactivation) functions respectively.

Guess you like

Origin blog.csdn.net/xinTianou123/article/details/127927613