【Vue3】Reactive 全家桶

Reactive

  • ref支持所有类型,reactive 只支持引用类型 Array,Object,Map,Set
  • ref取值、赋值都需要.value,而reactive不需要
  • reactive 不能直接赋值 否则破坏响应式对象
    • 解决方法一:数组使用push加 解构
    • 解决方法二:添加一个对象,把数组作为一个属性去解决
<template>
  <div>
    <!-- 表单 -->
    <!-- <form>
      <input v-model="form.name" type="text">
      <br>
      <input v-model="form.age" type="text">
      <br>
      <button @click.prevent="submit">submit</button>
    </form> -->

    <!-- 数组 -->
    <ul>
      <li v-for="item in list.arr">{{ item }}</li>
    </ul>
    <button @click.prevent="add">add</button>
  </div>
</template>

<script setup lang="ts">
import { reactive } from 'vue';

//表单
// let form = reactive ({
//   name: 'vuee',
//   age: 24
// })
// form.age = 25

//数组
// let list = reactive([])
// 解决方法二
let list = reactive<{
  arr: string[]
}>({
  arr: []
})

const add = () => {
  // list.push('JDG')

  //异步获取数组
  setTimeout(() => {
    let res = ['EDG', 'RNG', 'JDG']
    // 不能直接赋值
    list.arr = res
    // 解决方法一
    // list.push(...res)
    console.log(list);

  }, 2000);
}
</script>

<style lang="scss" scoped></style>

readonly

<template>
  <div>
    <button @click="show">show</button>
  </div>
</template>

<script setup lang="ts">
import { reactive, readonly } from 'vue';
let obj = reactive({ name: 'xiaohu' })
const read = readonly(obj)
const show = () => {
  // read.name = 'dahu' 只读,不能修改
  obj.name = 'dahu'
  // obj可以修改
  console.log(obj);
}

</script>

<style lang="scss" scoped></style>

shallowReactive

shallowReactive也会被reactive影响

<template>
  <div>
    {{ obj }}
    <button @click="edit">edit</button>
  </div>
</template>

<script setup lang="ts">
import { shallowReactive } from 'vue';
let obj: any = shallowReactive({
  foo: {
    bar: {
      num: {
        name: 1
      }
    }
  }
})

const edit = () => {
  // obj.foo.bar.num.name = 2
  // 只能对foo层进行更改
  obj.foo = {
    name: 2
  }
  console.log(obj);

}

</script>

<style lang="scss" scoped></style>

你可能感兴趣的:(Vue,vue.js,javascript,前端)