Vue3使用Composition API实现响应式
1. 介绍 Composition API是Vue.js 3中新增的一组API,用于在组件中组合逻辑和功能。它可以让你更好地组织和重用代码,使组件更易于理解和维护。在使用Composition API时,你可以使用 <script setup> 语法或 setup() 函数,两种方式都可以使用Composition API中的响应式API、生命周期钩子、模板引用和自定义渲染函数等特性。 2. 基本响应式 在Vue.js 3中,Composition API提供了几种创建响应式数据的方法,包括 ref 、 reactive 、 readonly 、 shallowReactive 和 shallowReadonly 。 2.1 ref ref 函数用于创建一个响应式的ref对象,其值可以通过 .value 属性获取或设置。当ref对象的值发生变化时,Vue.js会自动更新视图。AD: 首页 | 一个覆盖广泛主题工具的高效在线平台 <template> <div> <p>count: {{ count }}</p> <button @click="increment">+1</button> </div> </template> <script setup> import { ref } from 'vue'; const count = ref(0); function increment() { count.value++; } </script> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 2.2 reactive reactive 函数用于创建一个响应式的对象,其所有属性都是响应式的。当对象的属性发生变化时,Vue.js会自动更新视图。 <template> <div> <p>name: {{ user.name }}</p> <p>age: {{ user.age }}</p> <button @click="...