Reactive

下面是reactive的基本用法

1
2
3
4
5
let form = reactive({
name: '123'
})

form.name = '321'

reactive不能直接赋值,会导致破坏响应式对象,因为reactive是proxy代理对象
数组可以使用push + 解构来赋值

1
2
3
4
let list = reactive<string[]>([])

list = ['123'] // X
list.push(...['123']) // √

或者可以像这样也可以赋值

1
2
let list = reactive<{arr: string[]}>({arr: []})
list.arr = ['123']

当然还有这种

1
2
let list = reactive<{arr: string[]}>({arr: []})
Object.assign(list,{arr: ['123']})

那么它跟ref的区别是什么呢

  1. ref支持所有类型,而reactive只支持引用类型如:Array,Object,Map,Set
  2. ref取值赋值需要.value,而reactive不需要

readonly

只读的意思,这样对象就只读了

1
2
3
4
5
6
7
8
9
import {readonly} from 'vue'

const obj = reactive({name: '123'})
const read = readonly(obj)

const change = () => {
read.name = '321'
console.log(obj,read)
}

shallowReactive

浅层次的Reactive,当然也和ref和shallowRef一样,只要页面上有reactive被更改,页面也会重新渲染,导致shallowReactive深层次的更改在页面上更新

1
2
3
4
5
6
7
8
9
10
11
12
import {shallowReactive} from 'vue'

const shallow = shallowReactive({
name: {
age: 12
}
})

const change = () => {
shallow.name.age = 17 // 不会触发更新
shallow.name = {age: 18} //会触发更新
}

Reactive源码解析

还没想好怎么写

reactive中如果传入基本类型会被抛出,并返回错误信息

1
2
3
if(!isObject(target)) {
...
}