# Vue: composition API vs option API tags:Vue ### option API 在Vue2中,我們會依以下原則做分類: `data` : 存放資料 `methods`: 功能邏輯 `computed`: 資料計算 但在同一個元件中,很可能處理很多件事 假設有事件A.B.C, data裡面有A.B.C的資料,methods裡面有A.B.C的邏輯方法,computed裡面有A.B.C的計算,如果只想看A相關的程式,需要到不同的地方找,換句話說,A的程式散落各處,在維護上較為不便。 ### composition API Vue參考React後做的更新,以功能邏輯來做拆分,易讀性增加,只改變js的部分 #### 起手式 通常會使用ESM做搭配 ```javascript= //引入ESM import { createApp, ref, reactive, onMounted, computed} from 'https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.0-beta.7/vue.esm-browser.min.js' export default { setup() { //讓模板可以存取的要放到return裡 return {} } } ``` `ref` : 同data(不受型別限制) `reactive` : 同data(只能放物件) `onMounted` : 同mounted `computed` : 同computed methods則直接以function形式呈現 ### ref, reactive 的操作 ```javascript= const test = ref('test content') const test2 = reactive({}) //回傳值 return { test, test2 } ``` ==ref 可以放任何型別的資料!== 取值要使用`.value` ### onMounted 的操作 ```javascript= //加入生命週期 onMounted(() => { //do something }) ``` ### computed 的操作 ```javascript= const aaa = computed(() => { //do something }) ``` ### Vue2 的 this 指向 Vue是由 new一個實例產生的,在methods裡的this是指向Vue的實例,但是如果是箭頭函式的this則是指向window,因此在Vue文件中也不建議methods用箭頭函式寫 ### Vue3 消失的 this 因為setup在生命週期beforeCreate和created前執行,此時vue對象還沒創建,因此無法在Vue3中使用this。 ==在 setup 中無法使用 beforeCreate 及 created== | Hooks 名稱 (Vue 2.x/3.x) | Hooks 名稱 (對應 Vue 3.0 Composition API) | 說明 | | -------- | -------- | -------- | | beforeCreate | setup() | Vue 實體被建立,狀態與事件都尚未初始化 || -------- | -------- | -------- | | created | setup() | Vue 實體已建立,狀態與事件已初始化完成(prop、data、computed 等屬性已建立,vm.$el 屬性無法使用 ) |