vue中 钩子函数如何使用async?

  async created () {
    await setTimeout(()=>{
      console.log(1)
    },5000);
  },
  async mounted () {
    console.log(2)
  }

在vue中给created使用async await,还是会先输出2,而不是等1输出完?

阅读 22.8k
2 个回答

可以变相达到这个目的

  async created () {
    this.create_promise = new Promise(resolve=>this.create_promise_resolve=resolve);
    setTimeout(()=>{
        console.log(1);
        this.create_promise_resolve();
    },1000)
  },
  async mounted () {
    await this.create_promise;
    console.log(2)
  }

你要理解,所有的鉤子函數都只是在指定時間執行而已,框架並不關心它們執行的結果,所以你這種做法無法滿足你的需求。

建議你根據需求調整實現。

推荐问题