在vue3.x版本中,setup函数就是vue3 组合式API的入口,换句话说就是在setup中的写的代码,就是组合式API 的写法。下面总结常用的与响应式相关的api, 帮助您在 Vue 3 中创建响应式应用程序。
reactive()和ref():- 创建响应式对象和引用。
- 例子:
const state = reactive({ count: 0 });
computed():- 创建计算属性。
- 例子:
const doubleCount = computed(() => count.value * 2);
watch():- 监听响应式值的变化。
- 例子:
watch(() => count.value, (newVal) => console.log(Count changed to ${newVal}));
watchEffect():- 监听响应式值的变化并执行函数。
- 例子:
watchEffect(() => console.log(Count is ${count}));
provide()和inject():- 提供和注入组件之间的依赖项。
- 例子:
provide('count', ref(0));和const count = inject('count');
更多Vue3 API请参考官网:https://cn.vuejs.org/api/