2.vue3之reactive全家桶

你应该离开舒适的床, 起来坐在冰冷的板凳上, 提什修为.

1. reactive()

于ref的区别:

  1. ref支持所有的类型, 而reactive只支持引用类型 Array Object Map Set
let form = reactive({
    name: '鲁班七号',
    age: 12
})
// 定义类型
type M = {
    name: string
    age: number
}
let form = reactive<M>({
    name: '鲁班七号',
    age: 12
})
  1. ref取值、赋值都需要加.value, 而reactive不需要
form.age = 18
  1. reactive是使用的proxy代理的, 不能直接赋值, 否则会破坏其响应式对象
<ul>
  <li v-for="item in list">{{item}}</li>
</ul>
<button @click=add>提交</button>


let list = reqctive<string[]>([])
const add = () => {
  setTimeout(() => {
    let res = ['伽罗', '香香', '阿狸']
    list = res
    console.log(res); // 此时数组是有值, 但是页面视图不会更新!
  }, 2000);
}

解决方案:

// 1. 使用数组的方法加es6语法
const add = () => {
  setTimeout(() => {
    let res = ['伽罗', '香香', '阿狸']
    list.push(...res)
    console.log(res);
  }, 2000);
}

// 2. 改变数据结构为对象形式,把数组作为一个属性解决
<ul>
  <li v-for="item in list.arr">{{item}}</li>
</ul>
<button @click=add>提交</button>

let list = reactive<{arr: string[]}>({arr: []})
const add = () => {
  setTimeout(() => {
    let res = ['伽罗', '香香', '阿狸']
    list.arr = res
    console.log(res);
  }, 2000);
}

2. readonly()

把reactive中的属性变为只读的

let obj = reactive({name: '香香'});
const read = readonly(obj)
read.name = '狼狗'  // 报错, 无法修改, 因为是只读的

readonly()会受reactive的影响的

<button @click=show>修改</button>

const show = () => {
  // read.name = '狼狗';    // 无法修改, 只读的
  obj.name = '狼狗';   // 可以修改, 并且read也会跟着修改
  console.log(obj,read);
}

3. shallowReactive()

效果和 shallowRef 是一样的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值