## 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);
}
}
```