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>

相关推荐
一 乐8 小时前
婚纱摄影网站|基于ssm + vue婚纱摄影网站系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·后端
C_心欲无痕8 小时前
ts - tsconfig.json配置讲解
linux·前端·ubuntu·typescript·json
清沫8 小时前
Claude Skills:Agent 能力扩展的新范式
前端·ai编程
yinuo9 小时前
前端跨页面通信终极指南:方案拆解、对比分析
前端
北辰alk9 小时前
Vue 模板引擎深度解析:基于 HTML 的声明式渲染
vue.js
北辰alk9 小时前
Vue 自定义指令完全指南:定义与应用场景详解
vue.js
yinuo9 小时前
前端跨页面通讯终极指南⑨:IndexedDB 用法全解析
前端
北辰alk9 小时前
Vue 动态路由完全指南:定义与参数获取详解
vue.js
北辰alk10 小时前
Vue Router 完全指南:作用与组件详解
vue.js
北辰alk10 小时前
Vue 中使用 this 的完整指南与注意事项
vue.js