Composition API: setup()
• 2 • 228
April 11, 2022此篇將紀錄 vue3 LifeCycle 一個比較大的改動,也就是 Composition API。 由於工作上還是使用 vue2,因此本篇會順便介紹 vue2 與 vue3 這部分的差異性。
vue2 LifeCycle
vue2 總共有 8 個 hook,網上有非常多講解 LifeCycle 的文章,這裡就不再貼測試每個 hook 的程式碼,直接快速帶過。 正常情況下會經歷四個 hook(beforeCreate、created、beforeMount 及 mounted),分別是以下的狀況:
- beforeCreate:el 和 data 並未初始化,還是 undefind 的狀態
- created:此時完成了 data 的初始化,el 還沒有建立
- beforeMount:完成了 el 和 data 的初始化
- mounted:el 掛載完成
若 data 有被更新,則會觸發 beforeUpdate 與 updated。
最後 beforeDestroy 及 destroyed 作者比較少用,但若有 el 需要此功能,可使用destroy()
,此 el 被銷毀後這時 el 中的任何定義( data 、 methods…等)都已被解除綁定,代表在此做的任何操作都會失效,而整個 LifeCycle 最後能對 el 做事情的 hook 就是 beforeDestroy。
vue3 LifeCycle
進入到 vue3 後,LifeCycle hook function 的寫法有所改變,下面就直接來看一下新做法吧。
定義 setup 函式
首先要定義 setup 函式,這個函式包含 data、methods、computed、lifecycle 等方法。
<script>
import json from "../demo.json";
import card from "./components/v-card/misc-media-width-text.vue";
import {
ref,
reactive,
onBeforeMount,
onMounted,
onBeforeUpdate,
onUpdated,
computed,
} from "vue";
export default {
name: "App",
components: {
card,
},
setup() {
const ApiData = reactive([]);
const uri = ref("");
const computedFun = computed(() => {
return ApiData[0].length;
});
onBeforeMount(() => {
// DOM 渲染前
console.log("DOM 渲染前");
});
onMounted(() => {
// DOM 渲染完成後
if (process.env.VUE_APP_ENV === "dev") {
uri.value = process.env.VUE_APP_API_ENDPOINT_DEV;
this.axios
.get(`${uri.value}`)
.then((response) => {
ApiData.push(response.data.attractions);
})
.catch((error) => {
console.log(error);
});
} else {
ApiData.push(json.attractions);
}
});
onBeforeUpdate(() => {
// 在資料更改導致virtual DOM重新渲染前調用
console.log("資料更改前");
});
onUpdated(() => {
// 在資料更改導致virtual DOM重新渲染後調用
console.log("資料更改後");
});
return {
ApiData,
uri,
computedFun,
};
},
methods: {},
};
</script>