reactive

用来绑定复杂的数据类型 例如 对象 数组
reactive 源码约束了我们的类型
image.png
他是不可以绑定普通的数据类型这样是不允许 会给我们报错

  1. import { reactive} from 'vue'
  2. let person = reactive('sad')

image.png
绑定普通的数据类型 我们可以 使用昨天讲到ref
你如果用ref去绑定对象 或者 数组 等复杂的数据类型 我们看源码里面其实也是 去调用reactive
使用reactive 去修改值无须.value

reactive 基础用法

  1. import { reactive } from 'vue'
  2. let person = reactive({
  3. name:"小满"
  4. })
  5. person.name = "大满"

数组异步赋值问题
这样赋值页面是不会变化的因为会脱离响应式

  1. let person = reactive<number[]>([])
  2. setTimeout(() => {
  3. person = [1, 2, 3]
  4. console.log(person);
  5. },1000)

解决方案1
使用push

  1. import { reactive } from 'vue'
  2. let person = reactive<number[]>([])
  3. setTimeout(() => {
  4. const arr = [1, 2, 3]
  5. person.push(...arr)
  6. console.log(person);
  7. },1000)

方案2
包裹一层对象

  1. type Person = {
  2. list?:Array<number>
  3. }
  4. let person = reactive<Person>({
  5. list:[]
  6. })
  7. setTimeout(() => {
  8. const arr = [1, 2, 3]
  9. person.list = arr;
  10. console.log(person);
  11. },1000)

readonly

  1. 拷贝一份proxy对象将其设置为只读
  2. import { reactive ,readonly} from 'vue'
  3. const person = reactive({count:1})
  4. const copy = readonly(person)
  5. //person.count++
  6. copy.count++

shallowReactive

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

  1. <template>
  2. <div>
  3. <div>{{ state }}</div>
  4. <button @click="change1">test1</button>
  5. <button @click="change2">test2</button>
  6. </div>
  7. </template>
  8. <script setup lang="ts">
  9. import { shallowReactive } from 'vue'
  10. const obj = {
  11. a: 1,
  12. first: {
  13. b: 2,
  14. second: {
  15. c: 3
  16. }
  17. }
  18. }
  19. const state = shallowReactive(obj)
  20. function change1() {
  21. state.a = 7
  22. }
  23. function change2() {
  24. state.first.b = 8
  25. state.first.second.c = 9
  26. console.log(state);
  27. }
  28. </script>
  29. <style>
  30. </style>

————————————————
版权声明:本文为CSDN博主「小满zs」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq1195566313/article/details/122784094