使用 Vue.js 和 vue-router 构建 SPA 时如何销毁组件?
How to destroy a component when building SPA with Vue.js and vue-router?
假设我有一个如下所示的路由器映射:
router.map({
'/a_example': {
component: A
},
'/b_example': {
component: B
},
组件 A 每 1 秒有一个 Ajax 请求。我在浏览器中加载 /a_example
并单击 component A
上的 link 转到 /b_example
。现在浏览器正在按预期显示组件 B。但是,Ajax 请求不会停止,仍然每 1 秒发送一次请求。
我的猜测是 vue-router 仍然将组件 A 隐藏在引擎盖下,这样它就不会遇到性能问题。
无论如何,我在 http://vuejs.github.io/vue-router/en/view.html 中发现的就是这个 keep-alive
东西。但默认情况下它是停用的,我确定我没有使用它。
有什么我可以使用的选项吗?
Vue-router 提供了一些可选的transition hooks。您可以停止在 deactivate
挂钩内发送 ajax 请求。
Vue.component('component-A', {
route: {
deactivate: function () {
//stop sending requests
}
}
})
在最新版本的 VueRouter (v.2.1.1) 中,您可以使用 In-Component Guard:
离开路线前
const Foo = {
template: `...`,
beforeRouteLeave (to, from, next) {
// stop your requests here
// ...
next()
}
}
假设我有一个如下所示的路由器映射:
router.map({
'/a_example': {
component: A
},
'/b_example': {
component: B
},
组件 A 每 1 秒有一个 Ajax 请求。我在浏览器中加载 /a_example
并单击 component A
上的 link 转到 /b_example
。现在浏览器正在按预期显示组件 B。但是,Ajax 请求不会停止,仍然每 1 秒发送一次请求。
我的猜测是 vue-router 仍然将组件 A 隐藏在引擎盖下,这样它就不会遇到性能问题。
无论如何,我在 http://vuejs.github.io/vue-router/en/view.html 中发现的就是这个 keep-alive
东西。但默认情况下它是停用的,我确定我没有使用它。
有什么我可以使用的选项吗?
Vue-router 提供了一些可选的transition hooks。您可以停止在 deactivate
挂钩内发送 ajax 请求。
Vue.component('component-A', {
route: {
deactivate: function () {
//stop sending requests
}
}
})
在最新版本的 VueRouter (v.2.1.1) 中,您可以使用 In-Component Guard:
离开路线前
const Foo = {
template: `...`,
beforeRouteLeave (to, from, next) {
// stop your requests here
// ...
next()
}
}