VUE 3 COMPOSITION API
CHEAT SHEET(中⽂版)
<template>
Use the composition API when:
以下情况适于使用 Composition API:
<div>
The component is too large, and
组件过大,且应该以逻辑关注点
<p>Spaces Left: {{ spacesLeft }}
out of {{ capacity }}</p>
should be organized by logical
(或特性)的维度被管理时。
<h2>Attending</h2>
concerns(feature).
<ul>
AND / OR
<li
v-for="(name, index) in attending" :key="index">
Code needs to be extracted and reused
作为Mixins或Scoped Slots的代替,
{{ name }}
across mulitiple components, as an
代码须提取出来以在多组件间
复用。
</li>
alternative to Mixins/Scoped Slots.
</ul>
AND / OR
<button @click="increaseCapacity()">Increase Capacity</button>
Type safety in TypeScript is important.
在TypeScript中类型安全很重
要
时。
</div>
</template>
If using Vue 2 with Composition
API plugin configured:
如果正在用 Vue 2 且已经设置好了 Composition API 插件:
<script>
import { ref, computed } from "vue";
export default {
import { ref, computed } from
"@vue/composition-api";
setup() {
Reactive Reference
const capacity = ref(4);
const attending = ref(["Tim", "Bob",
"Joe"]);
const spacesLeft = computed(() =>
{
return capacity.value
- attending.value.length;
});
将基
本类型包裹在对象中,以跟踪其变化
Computed Property
.value
通过调用 .value 访问一个 Reactive Reference 的值
function increaseCapacity() {
capacity.value++;
}
Methods declared as functions
用函数声明方法,相当于原
`Methods`
return { capacity, attending, spacesLeft, increaseCapacity };
}
};
可被 template 访问的各种对象和函数
</script>
也可以写成:
CAN ALSO BE WRITTEN AS:
import { reactive, computed, toRefs }
from "vue";
export default {
调用 reactive() 以使对象变为反应式的
Reactive takes an object and returns a
reactive object
setup() {
const event = reactive({
capacity: 4,
attending: ["Tim",
"Bob", "Joe"],
spacesLeft: computed(() => { return event.capacity - event.attending.length; })
});
.value
function increaseCapacity() {
因为对象是
反应式的,所以用不着
.value
Notice we don’t have to use
event.capacity++;
toRefs
return { ...toRefs(event),
increaseCapacity };
用 toRefs() 将反应式对象变回普
通对象
}
}
};
Watch the Vue 3 Essentials course on VueMastery.com