如何判断是否已卸载Vue组件以防止异步功能访问已卸载组件的数据?

时间:2020-01-10 12:31:10

标签: javascript vue.js

请参阅此最小示例

import Vue from 'vue';

Vue.extend({
  data() {
    return {
      name: 'James',
    };
  },
  methods: {
    greet() {
      setTimeout(() => {
        const componentIsUnmounted = ???; // How do I tell if component is unmounted?

        if (!componentIsUnmounted) {
          console.log(this.name);
        }
      }, 300);
    },
  },
});

如您所见,我有一个带有异步功能的组件,当您调用它时,将在300ms后触发它,届时Vue组件可能已卸载。

我想我可以通过在Lodash的uniqueID()函数中将标记存储在全局变量中来在mounted()beforeDestroyed()处创建唯一ID来实现。

还有另一种更简单的方法吗?

2 个答案:

答案 0 :(得分:1)

我认为最好控制超时(例如,使用clearTimeout(),如注释中所建议)。在您的情况下,当您使用debounce时,取决于所使用的库,您可能没有该控件。

在这种情况下,一个建议是将Node.containsvm.$el混合使用。如下:

export default {
  methods: {
    greet() {
      const isUnmounted = !document.body.contains(this.$el)
    }
  }
}

另一种选择是使用destroyed生命周期在内部控制此状态。


我提供了一个可能帮助您的指导示例:https://codesandbox.io/s/smoosh-frost-fdisj


希望有帮助!

答案 1 :(得分:0)

您可以使用如下所示的beforeDestroy事件:

  mounted() {
    this.$once("hook:beforeDestroy", () => {
      //...
    })
  }