请参阅此最小示例
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来实现。
还有另一种更简单的方法吗?
答案 0 :(得分:1)
我认为最好控制超时(例如,使用clearTimeout()
,如注释中所建议)。在您的情况下,当您使用debounce
时,取决于所使用的库,您可能没有该控件。
在这种情况下,一个建议是将Node.contains
与vm.$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", () => {
//...
})
}