Vue 3 Composition API

前言
這裡將會記錄參加 六角學院 Vue 3 新手夏令營(活動已結束) 課程筆記 與 每日任務紀錄,第四周介紹如何使用 Composition API 與 watch 功能,並了解 Vue 2 與 Vue 3 的差異。
課堂重點
- Option API 與 Composition API 的差異
- 了解 Vue 裡面 this 的指向
- 生命週期的使用
- ref 與 reative 的差別 ( 略提 )
Option API
- 所有功能被依據程式邏輯區分
- 對初學者來說相當易學
- 缺點:商業、功能邏輯被拆分到各處

- 藍色代表程式邏輯
- 綠色與紅色分別為同一個功能所需要用的邏輯
Option API 與 Composition API 的差異
- 而 Composition 改善其缺點,將同一個商業、功能邏輯寫在一起

- 將分散在各處的功能邏輯集中在一起 (分散在各處的顏色集中在一起)
Composition API
- 全部整合進
setup()
內
- 高度的彈性
- 基於既有的 JS 知識開發
- 方便引入函式庫
- 所有功能邏輯都各自寫好,不會分散各地

Vue 的 this 指向
- Proxy 是 Vue 在做雙向綁定的重要結構
- 在 Option API 可以不知道他
- 但在 Composition API 他還蠻重要的
- 資料都會放在 Target 裡面

複習 ESM
CDN 連結
https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.0-beta.7/vue.esm-browser.min.js

Composition API 起手式
通常都是使用 ESModule 來操作
不轉ESM也行,但在composition API使用ESM更符合模組化概念
1 2 3 4 5
| <div id="app"> {{ text }} <input type="text" v-model="text"> </div>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <script type="module"> import { createApp } from 'https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.0-beta.7/vue.esm-browser.min.js' const app = createApp({ setup() { const text = '卡斯伯棒棒'; return { text } } }); app.mount('#app'); </script>
|

Composition API 裡雙向綁定,需要引入ref
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <script type="module"> import { createApp, ref } from 'https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.0-beta.7/vue.esm-browser.min.js' const app = createApp({ setup() { const text = ref('卡斯伯棒棒'); return { text } } }); app.mount('#app'); </script>
|
Composition API 使用函式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <script type="module"> import { createApp, ref } from 'https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.0-beta.7/vue.esm-browser.min.js' const app = createApp({ setup() { const text = ref('卡斯伯棒棒'); function getText() { console.log( text ) } return { text, getText, } } }); app.mount('#app'); </script>
|
Composition API 使用生命週期
引入 onMounted
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| <script type="module"> import { createApp, ref, onMounted } from 'https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.0-beta.7/vue.esm-browser.min.js' const app = createApp({ setup() { const text = ref('卡斯伯棒棒'); function getText() { console.log( text ) } onMounted(()=>{ getText() }) return { text, getText, } } }); app.mount('#app'); </script>
|
引入 computed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <script type="module"> import { createApp, ref, onMounted, computed } from 'https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.0-beta.7/vue.esm-browser.min.js' const app = createApp({ setup() { const num = ref(1); const doubleNum = computed(()=>{ return num.value * 2 }) return { num, doubleNum, } } }); app.mount('#app'); </script>
|

reative 與 ref 的差別

reative
- 非常標準的 Proxy 物件
- 限制只能放物件
- 覆蓋後會出現不可預期的錯誤
ref
- 沒有任何型別的限制
- 會依據放入的型別,而有不同的調整
- 一定要使用
.value
取值
參考資料