vue.js:异步钩子的替代品

Cra*_*hax 2 javascript async-await vue.js

假设我编写了一个 vue.js 组件,并且我想使用包含一些异步操作的生命周期钩子(在本例中为“销毁”)。我不想在异步操作完全提交之前离开钩子。一种选择是使用 Javascript 的异步等待功能。

    export default {
      name: 'someComponent',
      data() {
        return {
          ...,
        };
      },
      async destroyed() {
         await someAsyncOperation()
     }
    }
Run Code Online (Sandbox Code Playgroud)

我想问是否有任何方法可以在没有异步等待的情况下做到这一点(也许是承诺)。

zer*_*298 5

Vue 不关心也不承认你的生命周期钩子是异步的,它不会等待它们。考虑下面的例子。如果 API 按照您解释的方式工作,则在打印thing之后您才会看到新的内容console.log。然而,它立即出现。

此外,Vue 文档没有声明生命周期挂钩是异步的。它没有说它们是async,也没有提供回调选项来推断挂钩何时完成。

这与 Vue 具有的其他一些钩子 API(如动画)形成对比。

const $timeout = d => new Promise(r => setTimeout(r, d));

const thing = {
  template: "<div>Count: {{text}}</div>",
  data() {
    return {
      text: "foo"
    };
  },
  async created() {
    await $timeout(1000);
    console.log("hello");
  },
  async destroyed() {
    await $timeout(1000);
    console.log("goodbye");
  }
}

const app = new Vue({
  el: "#app",
  components: {
    thing
  },
  data() {
    return {
      things: []
    }
  },
  methods: {
    addThing() {
      this.things.push({});
    },
    removeThing() {
      this.things.pop();
    }
  }
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>

<div id="app">
  <button @click="addThing">+</button>
  <button @click="removeThing">-</button>
  <div v-for="thing in things">
    <thing></thing>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)