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

Jos*_*ang 6 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);
    },
  },
});

Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我有一个带有异步函数的组件,当你调用它时,它会在300ms后被触发,到那时,Vue组件可能会被卸载。

我想我可以通过 Lodash 的函数在全局中存储一个标志来在和uniqueID()处创建一个唯一的 ID 来做到这一点。mounted()beforeDestroyed()

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

Wil*_*ins 1

我认为如果您可以控制超时(clearTimeout()例如,按照评论中的建议使用 ),那将是最好的。在您的情况下,当您使用 a 时debounce,根据您使用的库,您可能没有这种控制权。

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

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

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


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


希望能帮助到你!