[TOC]
### 1. 生命周期鉤子函數理解
vue生命周期會按照 `beforeCreate`、`created`... 順序進行,但生命周期鉤子函數內部執行時可能不會按照順序執行(在有異步代碼執行時)
~~~
created() {
console.log(1);
this.testAsync();
},
mounted() {
console.log(3);
},
methods: {
testAsync() {
setTimeout(() => {
console.log(2);
}, 3000)
}
}
// 1 3 2
~~~
### 2. created 與 mounted 請求數據
由于 `created` 特性(data observer、watch/event 配置完成),它可以做些數據初始化,例如:獲取配置文件數據、請求后臺數據。只要不涉及到 `dom` 均可在此時執行,對于需要在可以獲取到 `dom節點` 之后渲染數據的,可在 `mounted` 中執行,例如:繪制 `echarts` 圖
~~~
created() {
this.getLocalData();
},
mounted() {
this.drawTest();
},
methods: {
async getLocalData() {
const config = await getLocalData();
this.config = config;
},
async drawTest() {
const res = await getDrawData();
const params = {
chartId: "draw-test",
dataX: res,
...
};
this.drawFunction(params);
},
drawFunction({ chartId, chartName, dataX, dataY, extra }) {
const myEchart = window.echarts.init(document.getElementById(chartId));
...
}
}
~~~