Vue mounted return Promise resolve
一進入頁面的時候要呼叫 API 取得資料進行呈現
執行順序為以下四個步驟:
- 在 Vue 定義了 mounted() 去呼叫 methods
- methods 則是透過 Promise 來取得 API 資料
- 將資料存入 data()
- template 調用 data
撰寫的時候則以取資料的部分開始進行:
-
呼叫 API 取得資料,透過 resolve 將資料取回
import { getBlogTypeTitle } from '@/api/blog' // 引用 API methods: { getTitle(type) { return new Promise((resolve, reject) => { getBlogTypeTitle(type) .then((response) => { resolve(response); // 傳回 response }) .catch((error) => { reject(error); }); }); } } -
data() 定義返回值
data(){ return{ vue: [], css: [] } }, -
mounted() 頁面讀取時呼叫 method,並使用 then 將 resolve 值存入 data 定義的返回值
mounted() { this.getTitle('Vue').then(response => (this.vue = response)) this.getTitle('CSS').then(response => (this.css = response)) }, -
template 調用 data
<template> <div class="content"> <div class="test"> <h4>Vue</h4> <div class="obj" v-bind:key="v.id" v-for="v in vue"> <p>{{ v.title }}</p> </div> </div> <div class="test"> <h4>CSS</h4> <div class="obj" v-bind:key="c.id" v-for="c in css"> <p>{{ c.title }}</p> </div> </div> </div> </template>
至此就設定完成了。
References
https://stackoverflow.com/questions/53513538/is-async-await-available-in-vue-js-mounted
https://book.vue.tw/CH1/1-7-lifecycle.html