title: Vue3使用Composition API实现响应式
date: 2024/5/29 下午8:10:24
updated: 2024/5/29 下午8:10:24
categories:
- 前端开发
tags:
- Vue3
- Composition
- Refs
- Reactive
- Watch
- Lifecycle
- Debugging
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>
2.2 reactive
reactive
函数用于创建一个响应式的对象,其所有属性都是响应式的。当对象的属性发生变化时,Vue.js会自动更新视图。
<template>
<div>
<p>name: {
{ user.name }}</p>
<p>age: {
{ user.age }}</p>
<button @click="incrementAge">+1</button>
</div>
</template>
<script setup>
import { reactive } from 'vue';
const user = reactive({
name: 'Alice',
age: 20
});
function incrementAge() {
user.age++;
}
</script>
2.3 readonly
readonly
函数用于创建一个只读的响应式对象,其所有属性都是只读的。当试图修改只读对象的属性时,会抛出一个错误。
<template>
<div>
<p>name: {
{ user.name }}</p>
<p>age: {
{ user.age }}</p>
</div>
</template>
<script setup>
import { reactive, readonly } from 'vue';
const user = reactive({
name: 'Alice',
age: 20
});
const readonlyUser = readonly(user);
// 会抛出一个错误
readonlyUser.age = 21;
</script>
2.4 shallowReactive
shallowReactive
函数用于创建一个浅响应式的对象,其所有属性都是响应式的,但其子对象的属性不是响应式的。
AD:专业搜索引擎
<template>
<div>
<p>name: {
{ user.name }}</p>
<p>age: {
{ user.age }}</p>
<p>address: {
{ user.address }}</p>
<button @click="incrementAge">+1</button>
<button @click="changeAddress">改变地址</button>
</div>
</template>
<script setup>
import { shallowReactive } from 'vue';
const user = shallowReactive({
name: 'Alice',
age: 20,
address: {
province: 'Beijing',
city: 'Beijing'
}
});
function incrementAge() {
user.age++;
}
function changeAddress() {
user.address = {
province: 'Shanghai',
city: 'Shanghai'
};
}
</script>
2.5 shallowReadonly
shallowReadonly
函数用于创建一个浅只