javascript - 如何判断 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()
还有另一种更简单的方法吗?
解决方案
我认为如果您可以控制超时(clearTimeout()
例如,按照评论中的建议使用),那将是最好的。在您的情况下,当您使用 adebounce
时,取决于您使用的库,您可能没有该控制权。
在这种情况下,一个建议是Node.contains
与vm.$el
. 如下:
export default {
methods: {
greet() {
const isUnmounted = !document.body.contains(this.$el)
}
}
}
其他替代方法是使用destroyed
生命周期在内部控制此状态。
我提供了一个可能对您有所帮助的指导性示例:https ://codesandbox.io/s/smoosh-frost-fdisj 。
希望能帮助到你!
推荐阅读
- python - ros melodic python2.7中gym的导入错误
- sql - 基于日期键的 SQL 求和列
- javascript - 组件数据流 [VueJS]
- python-3.x - 列表对象在 SVM 中不可调用
- hibernate - 如何根据条件在实体类中使用 Transient 关键字?
- c# - ASP.NET Core - 如何在 IIS 中托管后读取 EnvironmentVariableTarget
- c# - 接口重新实现的替代方案
- c++ - 静态网格与其他演员组件碰撞时调用函数 - 虚幻
- azure - Azure DevOps - 自动创建管道
- c# - List 是否需要 ReaderWriterLockSlim.EnterReadLock
。数数?