目錄
一、為什么需要Composition API?
二、核心概念:setup()?函數
三、響應式核心:ref()?和?reactive()
1.?ref?- 處理基本類型/對象
?2.?reactive?- 處理對象
四、生命周期鉤子新寫法
五、強大的邏輯復用:組合式函數
六、響應式計算:computed?&?watch
1. 計算屬性
?2. 偵聽器
七、最佳實踐指南
八、對比Options API?
結語
一、為什么需要Composition API?
在Vue2中,我們使用?Options API(data、methods、computed等選項)組織代碼。當組件功能復雜時,相同邏輯的代碼被分散到不同選項中,導致:
-
可讀性下降
-
邏輯復用困難(依賴mixins)
-
Typescript支持有限
Vue3的?Composition API?通過邏輯功能組合解決了這些問題,讓代碼更靈活、更可維護!
?
二、核心概念:setup()
?函數
Composition API的入口是?setup()
?函數,它在組件創建前執行,替代了Vue2的data()
、created()
等選項:
import { ref } from 'vue';export default {setup() {// 定義響應式數據const count = ref(0);// 定義方法const increment = () => {count.value++;};// 暴露給模板return { count, increment };}
}
?
關鍵點:
-
setup()
?在?beforeCreate
?前執行,沒有?this
-
返回對象中的屬性會暴露給模板使用
-
所有Composition API函數都需要在此引入
?
三、響應式核心:ref()
?和?reactive()
1.?ref
?- 處理基本類型/對象
const num = ref(0); // { value: 0 }
const user = ref({ name: 'Leo' });console.log(num.value); // 訪問值
num.value = 5; // 修改值
?2.?reactive
?- 處理對象
const state = reactive({count: 0,user: { name: 'Alice' }
});state.count = 10; // 直接修改屬性
特性 | ref | reactive |
---|---|---|
數據類型 | 任意 | 對象 |
模板訪問 | 自動解包 | 直接訪問屬性 |
重新賦值 | .value ?修改 | 不能直接替換對象 |
?
四、生命周期鉤子新寫法
在setup()
中使用生命周期前綴加on
:
import { onMounted, onUpdated } from 'vue';setup() {onMounted(() => {console.log('組件掛載完成!');});onUpdated(() => {console.log('組件更新了!');});
}
?
Vue2選項 | Composition API等價 |
---|---|
beforeCreate | setup() ?自身 |
created | setup() ?自身 |
mounted | onMounted |
updated | onUpdated |
?
五、強大的邏輯復用:組合式函數
將相同邏輯抽離為可復用函數(替代mixins):
// useCounter.js
import { ref } from 'vue';export default function useCounter() {const count = ref(0);const increment = () => count.value++;const decrement = () => count.value--;return { count, increment, decrement };
}
?在組件中使用:
import useCounter from './useCounter';setup() {const { count, increment } = useCounter();return { count, increment };
}
優勢:
-
顯式暴露使用的屬性和方法
-
多個組合函數互不沖突
-
完美支持TypeScript類型推斷
?
六、響應式計算:computed
?&?watch
1. 計算屬性
const doubleCount = computed(() => count.value * 2);
?2. 偵聽器
// 偵聽單個ref
watch(count, (newVal, oldVal) => {console.log(`計數變化:${oldVal} → ${newVal}`);
});// 偵聽多個源
watch([count, name], ([newCount, newName]) => {// 處理變化
});
七、最佳實踐指南
-
按功能組織代碼:將同一功能的
ref
、computed
、watch
放在一起 -
復雜組件使用
<script setup>
語法糖(SFC專屬):<script setup> import { ref } from 'vue'; const count = ref(0); // 自動暴露到模板 </script>
-
組合函數命名以
use
開頭(如useMouseTracker
) -
需要DOM時使用
ref
綁定元素:<template><div ref="root">元素</div> </template><script> import { ref, onMounted } from 'vue'; export default {setup() {const root = ref(null);onMounted(() => {console.log(root.value); // 獲取DOM元素});return { root };} } </script>
八、對比Options API?
// Options API (Vue2風格)
export default {data() {return { count: 0 }},methods: {increment() { this.count++ }},mounted() {console.log('mounted');}
}// Composition API (Vue3)
export default {setup() {const count = ref(0);const increment = () => { count.value++ };onMounted(() => console.log('mounted'));return { count, increment };}
}
?
結語
Composition API 賦予了Vue開發者更自由的代碼組織能力,尤其適合:
-
大型項目開發
-
需要高復用性的場景
-
TypeScript深度集成
雖然學習曲線稍陡峭,但它帶來的可維護性提升絕對值得投入!現在就開始重構你的Vue組件吧!
?