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>

相关推荐
宋辰月26 分钟前
学习react第三天
前端·学习·react.js
bug总结29 分钟前
更新原生小程序封装(新增缓存订阅)完美解决
前端·缓存·小程序
GISer_Jing37 分钟前
Node.js 开发实战:从入门到精通
javascript·后端·node.js
5335ld1 小时前
后端给的post 方法但是要求传表单数据格式(没有{})
开发语言·前端·javascript·vue.js·ecmascript
二川bro1 小时前
第33节:程序化生成与无限地形算法
前端·算法·3d·threejs
QDKuz1 小时前
掌握Vue2转Vue3, Options API 转 Composition API
前端·javascript·vue.js
老前端的功夫1 小时前
前端Echarts性能优化:从卡顿到流畅的百万级数据可视化
前端·javascript
进击的野人1 小时前
深入解析localStorage:前端数据持久化的核心技术
前端·javascript
懵圈1 小时前
第2章:项目启动 - 使用Vite脚手架初始化项目与工程化配置
前端
Mh1 小时前
如何优雅的消除“if...else...”
前端·javascript