Vue3 Reactive和Ref

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

1. ref

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

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

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,都可以实现响应式数据的跟踪和更新,具体选择取决于你的需求。

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山间漫步人生路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值