Vue 生命周期與 async await - daniel-qa/Vue GitHub Wiki

Vue 生命周期與 async/await

在 Vue 2 的生命周期中:

  • created(), mounted() 等:只能用 Promise 鏈式或直接調用

  • 普通 methods:可以用 async/await

  • Vue 3:生命周期可以用 async/await

Vue 2 生命周期鉤子

created(), mounted(), beforeDestroy() 等

❌ 不能直接宣告 async created() {}

✅ 可以在裡面呼叫 async methods

✅ 可以用 .then()/.catch()

export default {
  created() {
    // ❌ 不能寫 async created() {}
    this.loadData()  // ✅ 呼叫 async method
    
    // ✅ 或者用 Promise 鏈式
    this.loadData()
      .then(() => console.log('載入完成'))
      .catch(err => console.error(err))
  },
  
  methods: {
    async loadData() {
      try {
        const res = await fetch('/api')
        this.data = await res.json()
      } catch (error) {
        console.error('載入失敗:', error)
      }
    }
  }
}