技术文摘
Vue3 中 setup、ref、reactive 的使用方法
2025-01-10 20:36:28 小编
Vue3 中 setup、ref、reactive 的使用方法
在 Vue3 的世界里,setup、ref 和 reactive 是极为重要的特性,极大地改变了我们构建组件的方式。
首先来看看 setup 函数。它是 Vue3 组件中的一个新选项,在组件创建之前执行。setup 接收两个参数:props 和 context。props 是组件接收到的属性,而 context 包含了 attrs、slots 和 emit 等对象。setup 函数可以返回一个对象,这个对象中的属性和方法都可以在模板中使用。例如:
<template>
<div>{{ message }}</div>
</template>
<script setup>
import { ref } from 'vue';
const message = ref('Hello, Vue3!');
</script>
这里 setup 函数简洁明了地定义了一个响应式数据 message 供模板使用,让代码结构更加清晰。
接着讲讲 ref。ref 用于创建一个响应式的引用。它接收一个初始值,可以是任何类型。通过.value 来访问和修改其内部的值。在模板中使用时,不需要显式地写.value。比如:
<template>
<button @click="increment">{{ count }}</button>
</template>
<script setup>
import { ref } from 'vue';
const count = ref(0);
const increment = () => {
count.value++;
};
</script>
在上述代码中,count 是一个 ref 定义的响应式变量,点击按钮时,通过修改 count.value 来更新视图。
最后是 reactive。reactive 用于创建一个响应式的对象或数组。它接收一个普通对象,返回一个代理对象。对代理对象的属性修改会触发响应式更新。例如:
<template>
<div>
<p>{{ user.name }}</p>
<p>{{ user.age }}</p>
<button @click="updateUser">Update User</button>
</div>
</template>
<script setup>
import { reactive } from 'vue';
const user = reactive({
name: 'John',
age: 30
});
const updateUser = () => {
user.name = 'Jane';
user.age = 31;
};
</script>
这里 user 是 reactive 创建的响应式对象,点击按钮更新对象属性时,Vue 会自动更新视图。
setup 作为 Vue3 组件的入口函数,为组件逻辑提供了一个清晰的起始点。而 ref 和 reactive 则是创建响应式数据的强大工具,合理运用它们,能让我们更高效地开发 Vue3 应用。
- 无 Docker 缓存时构建镜像的方法介绍
- Docker 私有仓库 Harbor 搭建步骤
- 解决 docker-compose 启动镜像失败的若干方法
- Docker compose up -d 与 Docker restart 的差异
- Windows 中 wget 命令的下载与使用步骤
- Windows10 构建 FTP 服务器全流程指南
- docker-compose up -d 与 docker-compose up –build 的差异
- RocketMQ Streams 中 ILeaseService 的使用示例详解
- MAC 中以 Podman 替代 Docker 的详细使用指南
- 在 Docker 与 Kubernetes 中运用代理 IP 的操作指南
- Docker 本地镜像在阿里云的发布实现
- Windows Server 2019 中 DHCP 服务的验证及数据备份与恢复 Ⅲ
- VMware Fusion 虚拟机静态 IP 设置方法(最新推荐)
- Windows Server 2019 DHCP 服务器配置与管理之理论 Ⅰ
- Win10 中 FTP 服务器搭建的图文指南