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 应用。

TAGS: Vue3 Ref reactive Setup

欢迎使用万千站长工具!

Welcome to www.zzTool.com