• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

学习Vue3 第七章认识Reactive全家桶

武飞扬头像
小满zs
帮助1

reactive

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

reactive 源码约束了我们的类型

学新通

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

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

学新通

绑定普通的数据类型 我们可以 使用昨天讲到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.  
     
  6.  
    },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.  
     
  8.  
    },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.  
     
  12.  
    },1000)

readonly

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

  1.  
    import { reactive ,readonly} from 'vue'
  2.  
    const person = reactive({count:1})
  3.  
    const copy = readonly(person)
  4.  
     
  5.  
    //person.count
  6.  
     
  7.  
    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.  
     
  9.  
     
  10.  
     
  11.  
    <script setup lang="ts">
  12.  
    import { shallowReactive } from 'vue'
  13.  
     
  14.  
     
  15.  
    const obj = {
  16.  
    a: 1,
  17.  
    first: {
  18.  
    b: 2,
  19.  
    second: {
  20.  
    c: 3
  21.  
    }
  22.  
    }
  23.  
    }
  24.  
     
  25.  
    const state = shallowReactive(obj)
  26.  
     
  27.  
    function change1() {
  28.  
    state.a = 7
  29.  
    }
  30.  
    function change2() {
  31.  
    state.first.b = 8
  32.  
    state.first.second.c = 9
  33.  
    console.log(state);
  34.  
    }
  35.  
     
  36.  
     
  37.  
     
  38.  
     
  39.  
    </script>
  40.  
     
  41.  
     
  42.  
    <style>
  43.  
    </style>
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfjgahk
系列文章
更多 icon
同类精品
更多 icon
继续加载