【问题标题】:defer destroyed in vue lifecycle hook延迟在 vue 生命周期钩子中销毁
【发布时间】:2018-11-18 16:00:15
【问题描述】:

在我的组件中,我有一个 mounted 钩子,它以异步请求的形式获取一些数据:

mounted() {
  this.fetchData()
}

然后在beforeDestroy我从商店中删除数据:

beforeDestroy(){
  this.destroyDataInStore()
}

只要mounted 中的请求在组件开始拆除之前解决,这些就可以正常工作。

有什么办法可以推迟beforeDestroy 直到承诺在挂载中解决?

【问题讨论】:

  • 所以你实际上需要推迟销毁本身,而不是调用钩子,对吧?

标签: vue.js vuejs2


【解决方案1】:

你可以存储承诺:

export default {
    data () {
        return {
            thePromise: null
        }
    },
    mounted () {
        this.thePromise = this.fetchData()
    },
    beforeDestroy () {
        this.thePromise.then(() => {
            this.destroyDataInStore()
        })
    }
}

但为了确保一切正常,我会使用 created 钩子而不是 mounted 钩子:

export default {
    data () {
        return {
            thePromise: null
        }
    },
    created () {
        this.thePromise = this.fetchData()
    },
    beforeDestroy () {
        this.thePromise.then(() => {
            this.destroyDataInStore()
        })
    }
}

【讨论】:

  • 使用空承诺(Promise.resolve()) 来避免错误。但总的来说,我宁愿在这里使用可取消的甚至可观察的;问题在于 fetchData 的副作用。
  • 你会在哪里使用它?
  • 这只会推迟被销毁的数据,而不是实际的拆除。不幸的是,这并不能解决我遇到的问题
  • 基本上下一个被遍历的组件依赖于 store 在其挂载时为空
  • 只有当你的promise在组件被销毁时没有解决时,它才会延迟数据被销毁。如果 promise 已经被解析,它会直接销毁数据。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-16
  • 2018-04-23
  • 2021-03-26
  • 1970-01-01
  • 2020-01-15
  • 2017-11-22
  • 1970-01-01
相关资源
最近更新 更多