## Composition API 代碼 示例
Composition API的主要思想是,將它們定義為從新的`setup`函數返回的JavaScript變量,而不是將組件的功能定義為對象屬性。
```
import { ref, computed } from "vue";
export default {
setup() {
const count = ref(0);
const double = computed(() => count * 2)
function increment() {
count.value++;
}
return {
count,
double,
increment
}
}
}
```
## 代碼提取
使用Composition API重構上面定義的組件,定義功能在JavaScript模塊`useMixins`中
*在特性描述前面加上“use”是一種Composition API命名約定*
```
// useMixins.js
import { ref, computed } from "vue";
export default function () {
const count = ref(0);
const double = computed(() => count * 2)
function increment() {
count.value++;
}
return {
count,
double,
increment
}
}
```
## 代碼復用
要在組件中使用該函數,只需將模塊導入組件文件并調用它(注意導入是一個函數)。返回定義的變量,可以從`setup`函數中返回
```
import useMininx from "./useMixins.js";
export default {
setup() {
const { count, double, increment } = useMininx();
return {
count,
double,
increment
}
}
}
```
## 命名沖突解決
```
export default {
setup () {
const { someVar1, someMethod1 } = useCompFunction1();
const { someVar2, someMethod2 } = useCompFunction2();
return {
someVar1,
someMethod1,
someVar2,
someMethod2
}
}
}
```
## 隱式依賴解決
```
import useCompFunction from "./useCompFunction";
export default {
setup () {
// 某個局部值的合成函數需要用到
const myLocalVal = ref(0);
// 它必須作為參數顯式地傳遞
const { ... } = useCompFunction(myLocalVal);
}
}
```