vue3+ts 第四章(认识Reactive全家桶)

reactive

用来绑定复杂的数据类型 例如 对象 数组

reactive 源码约束了我们的类型

他是不可以绑定普通的数据类型这样是不允许 会给我们报错

import { reactive} from 'vue'

let person = reactive('sad')

绑定普通的数据类型 我们可以 使用昨天讲到ref

你如果用ref去绑定对象 或者 数组 等复杂的数据类型 我们看源码里面其实也是 去调用reactive

使用reactive 去修改值无须.value

reactive 基础用法

import { reactive } from 'vue'

let person = reactive({

name:"小满"

})

person.name = "大满"

数组异步赋值问题

这样赋值页面是不会变化的因为会脱离响应式

let person = reactive<number[]>([])

setTimeout(() => {

person = [1, 2, 3]

console.log(person);

},1000)

解决方案1

使用push

import { reactive } from 'vue'

let person = reactive<number[]>([])

setTimeout(() => {

const arr = [1, 2, 3]

person.push(...arr)

console.log(person);

},1000)

方案2

包裹一层对象

type Person = {

list?:Array<number>

}

let person = reactive<Person>({

list:[]

})

setTimeout(() => {

const arr = [1, 2, 3]

person.list = arr;

console.log(person);

},1000)

readonly

拷贝一份proxy对象将其设置为只读

import { reactive ,readonly} from 'vue'

const person = reactive({count:1})

const copy = readonly(person)

//person.count++

copy.count++

shallowReactive

只能对浅层的数据 如果是深层的数据只会改变值 不会改变视图

案例

<template>

<div>

<div>{{ state }}</div>

<button @click="change1">test1</button>

<button @click="change2">test2</button>

</div>

</template>

<script setup lang="ts">

import { shallowReactive } from 'vue'

const obj = {

a: 1,

first: {

b: 2,

second: {

c: 3

}

}

}

const state = shallowReactive(obj)

function change1() {

state.a = 7

}

function change2() {

state.first.b = 8

state.first.second.c = 9

console.log(state);

}

</script>

<style>

</style>

相关推荐
lecepin15 分钟前
AI Coding 资讯 2025-09-17
前端·javascript·面试
IT_陈寒18 分钟前
React 18实战:7个被低估的Hooks技巧让你的开发效率提升50%
前端·人工智能·后端
树上有只程序猿1 小时前
终于有人把数据库讲明白了
前端
猩兵哥哥1 小时前
前端面向对象设计原则运用 - 策略模式
前端·javascript·vue.js
司宸1 小时前
Prompt设计实战指南:三大模板与进阶技巧
前端
RoyLin1 小时前
TypeScript设计模式:抽象工厂模式
前端·后端·typescript
华仔啊1 小时前
Vue3+CSS 实现的 3D 卡片动画,让你的网页瞬间高大上
前端·css
江城开朗的豌豆1 小时前
解密React虚拟DOM:我的高效渲染秘诀 🚀
前端·javascript·react.js
vivo互联网技术1 小时前
拥抱新一代 Web 3D 引擎,Three.js 项目快速升级 Galacean 指南
前端·three.js