Vue3| 组合式API——reactive 和 ref 函数

发布时间 2023-10-13 22:20:23作者: 嘎嘎鸭2

Vue中默认的数据并不是响应式的,如果我们希望数据是响应式的,则需要通过 reactive 或者 ref 进行处理。

 

reactive ():

作用:接收 对象类型的数据作为参数传入 并返回一个 响应式对象

reactive 不能处理简单类型的数据

 

reactive 使用步骤:

1. 在 <script setup> 里,从 vue 包中导入 reactive

<script setup>
  import { reactive } from 'vue'
</script>

2. 在 <script setup> 中 执行 reactive 函数 并传入 类型为对象的初始值,并使用变量接收返回值

(在对象数据的外面包一层 reactive,一旦包完了之后,对象类型数据 得到的就是响应式的,再把响应式结果赋值给了 state)

<script setup>
import { reactive } from 'vue'

const state = reactive({
  count: 100
})

const setCount = () => {
  state.count++
}
</script>

<template>
  <div>{{ state.count }}</div>
  <button @click="setCount">加一</button>
</template>
 
---------------------------------------------------------------------------------------------------------
 
ref ():
作用:接收 简单类型或者对象类型的数据传入 并 返回一个响应式的对象
本质:在原有传入数据的基础上,外层包了一层对象,包成了复杂类型,再借助 reactive 实现的响应式
 

ref 使用步骤:

1. 在 <script setup> 里,从 vue 包中导入 ref 函数

<script setup>
import { ref } from 'vue'
</script>

2. 在 <script setup> 中 执行 ref 函数 并传入 初始值,使用变量接收 ref 函数的返回值

(返回的是对象,<script>中用 .value访问数据,但<template>中不需要加 .value)

<script setup>
import { ref } from 'vue'

const count = ref(20)

console.log(count.value)
</script>

<template>
  <div>{{ count }}</div>
</template>