首页 > 解决方案 > 如何判断 Vue 组件是否已卸载以防止异步函数访问已卸载组件的数据?

问题描述

请看这个最小的例子

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()处创建一个唯一 ID来做到这一点。mounted()beforeDestroyed()

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

标签: javascriptvue.js

解决方案


我认为如果您可以控制超时(clearTimeout()例如,按照评论中的建议使用),那将是最好的。在您的情况下,当您使用 adebounce时,取决于您使用的库,您可能没有该控制权。

在这种情况下,一个建议是Node.containsvm.$el. 如下:

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

其他替代方法是使用destroyed生命周期在内部控制此状态。


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


希望能帮助到你!


推荐阅读