Vue并不关心或承认您的生命周期挂钩是异步的,它不会等待它们。考虑下面的例子。如果API按照您解释它的方式工作,您将看不到新的API
thing
直到
console.log
此外,Vue文档没有声明生命周期挂钩是异步的。它并没有说他们是
async
并且它没有为回调提供一个选项来推断钩子何时完成。
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();
}
}
});
<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>