Vue3 Reactive和Ref

当你在使用Vue 3时,reactiveref 是两个常用的响应式API。它们都是用来跟踪状态变化并在UI中进行响应式更新的。

1. ref

ref 用于创建一个响应式的基本数据类型变量,例如数字、字符串等。它返回一个带有 .value 属性的对象,该属性包含了被包装的值。

javascript 复制代码
import { ref } from 'vue';

// 创建一个ref
const count = ref(0);

// 在模板中使用
<template>
  <div>{{ count.value }}</div>
  <button @click="increment">Increment</button>
</template>

// 在逻辑中使用
<script>
import { ref } from 'vue';

export default {
  setup() {
    // 创建一个ref
    const count = ref(0);

    // 定义一个函数来更新count
    const increment = () => {
      count.value++;
    };

    // 将数据和方法暴露给模板
    return {
      count,
      increment,
    };
  },
};
</script>

2. reactive

reactive 用于创建一个响应式的对象,可以跟踪对象内部属性的变化。它返回一个代理对象,你可以像操作普通对象一样操作它,但所有的改动都将被监视。

javascript 复制代码
import { reactive } from 'vue';

// 创建一个reactive对象
const state = reactive({
  count: 0,
  message: 'Hello',
});

// 在模板中使用
<template>
  <div>{{ state.count }}</div>
  <div>{{ state.message }}</div>
  <button @click="increment">Increment</button>
  <input v-model="state.message" />
</template>

// 在逻辑中使用
<script>
import { reactive } from 'vue';

export default {
  setup() {
    // 创建一个reactive对象
    const state = reactive({
      count: 0,
      message: 'Hello',
    });

    // 定义一个函数来更新count
    const increment = () => {
      state.count++;
    };

    // 将数据和方法暴露给模板
    return {
      state,
      increment,
    };
  },
};
</script>

无论是使用 ref 还是 reactive,都可以实现响应式数据的跟踪和更新,具体选择取决于你的需求。

相关推荐
问心无愧05132 小时前
ctf show web入门160 161
前端·笔记
李小白662 小时前
第四天-WEB服务器基本原理,IIS服务
运维·服务器·前端
humcomm3 小时前
AI编程时代新前端职位
前端·ai编程
好家伙VCC3 小时前
Web Components主题热切换方案揭秘
java·前端
甲维斯3 小时前
Kimi版超级玛丽效果“惊人”,配额不足5厘米!
前端·人工智能
hboot3 小时前
AI工程师第一课 - Python
前端·后端·python
凉菜凉凉3 小时前
AI时代,被抛弃的前端
前端·ai
console.log('npc')4 小时前
AI前端工程与生成式UI学习路线
前端·人工智能·ui
huangdong_4 小时前
淘宝商品SKU图自动分类技术深度解析:从DOM解析到智能归档
开发语言·javascript·ecmascript
梦曦i4 小时前
uni-router v1.1.1发布:守卫超时保护+路由监听
前端·uni-app