Vue基础(2)响应式基础

一. reactive()

在 Vue3 中,可以使用 reactive() 创建一个响应式对象或数组:

xml 复制代码
<script setup>
import { reactive } from 'vue'

const state = reactive({ count: 0 })
</script>

<template>
  <button @click="state.count++">
    {{ state.count }}
  </button>
</template>

需要注意的是,reactive() 返回的是一个原始对象的 Proxy,它与原始对象是不相等的。只有代理对象是响应式的,更新原始对象并不会触发更新。

js 复制代码
const row = {}
const proxy = reactive(raw)

console.log( proxy === row)  	// false

reactive() 的局限性

  • 有限的值类型:reactive() 只能用于对象、数组等对象类型,而不能用于基础数据类型(string、number、boolean)
  • 不能替换整个对象,会导致对初始引用的响应性连接丢失
xml 复制代码
<script setup>
import { reactive } from 'vue'

let state = reactive({ count: 0 })
const increase = () => {
  state = { count: 1 }		// state.count = 1 才能正确修改
}
</script>

<template>
  <button @click="increase">
    {{ state.count }}			<!-- 点击button,始终显示为0 -->
  </button>
</template>
  • 对解构操作不友好:将响应式对象的原始类型属性解构为本地变量时,或者将该属性传递给函数时,会丢失响应性。
xml 复制代码
<script setup>
import { reactive } from 'vue'

let state = reactive({ count: 0 })
let { count } = state

const increase = () => {
  count++
}
</script>

<template>
  <button @click="increase">
    {{ state.count }}		<!-- 点击button,始终显示为0 -->
  </button>
</template>

二. ref()

ref() 将传入的参数包装成一个带有 value 属性的 ref 对象。在模板中使用 ref 时,不需要附加 .value。

xml 复制代码
<script setup>
import { ref } from 'vue'

const count = ref(0)
console.log(count) 		// {value: 0},使用 count.value++
</script>

<template>
  <button @click="count++">
    {{ count }}			<!-- 无需.value -->
  </button>
</template>

ref() 的参数一般时基础数据类型,也可以是对象类型。如果参数是对象类型,系统会自动将 ref 转成 reactive。

xml 复制代码
<script setup>
import { ref } from 'vue'

const state = ref({ count: 0 })
console.log(state.value) 		// Proxy(object) {count: 0}
const increase = () => {
  state.value.count++
}
</script>

<template>
  <button @click="increase">	<!-- state.count++ -->
    {{ state.count }}			<!-- 无需.value -->
  </button>
</template>

一个包含对象的 ref 可以响应式地替换整个对象:

xml 复制代码
<script setup>
import { ref } from 'vue'

const state = ref({ count: 0 })
const increase = () => {
  state.value = { count: 1 }
}
</script>

<template>
  <button @click="increase">	
    {{ state.count }}			<!-- 点击button后由0变为1 -->
  </button>
</template>
相关推荐
李伟_Li慢慢5 小时前
02-从硬件说起WebGL
前端·three.js
kyriewen6 小时前
看了微软几万人用AI编程的数据——效率涨24%的代价没人提
前端·ai编程·claude
2601_963771376 小时前
How to Scale Your WordPress Store Traffic in 2026
前端·php·plugin
亿元程序员6 小时前
老板说我的3D箭头游戏用来做试玩太普通了,没人想玩,让我变点花样...
前端
李伟_Li慢慢6 小时前
01-threejs架构原理-课程简介
前端·three.js
_瑞8 小时前
深入理解 iOS 渲染原理
前端·ios
IT_陈寒8 小时前
SpringBoot自动配置失灵?你可能忘了这个关键注解
前端·人工智能·后端
碎碎念_4928 小时前
SpringBoot + Vue 前后端分离从 0 到 1 完整环境配置流程
vue.js·spring boot·后端
iCOD3R8 小时前
Skill - kill-ai-slop 解决“AI 味”样式
前端·css·ai编程
shuaijie05189 小时前
强制修改调用接口的api地址。
javascript·vue.js·ecmascript