【问题标题】:How to destroy a component when building SPA with Vue.js and vue-router?使用 Vue.js 和 vue-router 构建 SPA 时如何销毁组件?
【发布时间】:2016-12-13 14:36:45
【问题描述】:

假设我有一个路由器地图,如下所示:

router.map({
'/a_example': {
    component: A
},

'/b_example': {
    component: B
},

组件 A 上每 1 秒有一个 Ajax 请求。我在浏览器中加载 /a_example 并单击 component A 上的链接转到 /b_example。现在浏览器按预期显示组件 B。但是,Ajax 请求不会停止,并且仍然每 1 秒发送一次请求。

我的猜测是 vue-router 仍然将组件 A 隐藏在底层,这样它就不会遇到性能问题。

无论如何,我在http://vuejs.github.io/vue-router/en/view.html 中发现的只是keep-alive 的东西。但默认情况下它是停用的,我确定我没有使用它。

有什么我可以使用的选项吗?

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    Vue-router 提供了一些可选的transition hooks。您可以在 deactivate 挂钩内停止发送 ajax 请求。

    Vue.component('component-A', {
      route: {
        deactivate: function () {
        //stop sending requests
        }
      }
    })
    

    【讨论】:

      【解决方案2】:

      在最新版本的 VueRouter (v.2.1.1) 中,您可以使用In-Component Guard

      beforeRouteLeave

      const Foo = {
        template: `...`,
        beforeRouteLeave (to, from, next) {
          // stop your requests here
          // ...
          next()
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-03-14
        • 2021-03-17
        • 1970-01-01
        • 2020-09-21
        • 2020-04-05
        • 2019-12-04
        • 1970-01-01
        • 2017-11-20
        • 2020-09-24
        相关资源
        最近更新 更多