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

版权声明:本文为博主作者:山间漫步人生路原创文章,版权归属原作者,如果侵权,请联系我们删除!

原文链接:https://blog.csdn.net/weixin_43784341/article/details/137902699

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
青葱年少的头像青葱年少普通用户
上一篇 2024年4月22日
下一篇 2024年4月22日

相关推荐