vue3 之 ref、reactive

15 篇文章 0 订阅

1.ref、reactive的区别

reactive

  • 定义复杂类型响应式数据;
  • proxy类型,内部基于ES6的 proxy 实现;

ref

  • 定义一个响应式数据,普通类型和复杂类型都可;
  • 最外层:响应式依然是靠Object.defineProperty()的get与set完成的
  • 对象类型的数据:内部基于 proxy 实现;

2.注意事项

    ref、reactive变量可以监听到数据的变化,用时需注意不可直接替换变量。

//父组件
<template>
  <div style="color: #fff; font-size: 25px">
    <div>parent: {{ temp }}</div>
    <div class="button" @click="updateObj">1. 点我全量更换数据</div>
    <div class="button" @click="updateAttr">2. 点我添加属性</div>
    <div class="button" @click="updateData">3. 点我修改数据</div>

    <Child :temp="temp"></Child>
  </div>
</template>

<script>
import Child from "./child.vue";
import { ref, reactive } from "vue";

export default {
  name: "",
  components: { Child },
  setup() {
    let temp = reactive({ a: 1 }); // Proxy {a: 1}
    console.log("------create---temp: ", temp);

    function updateObj() {
      temp = { a: 1, b: 2 }; //此时reactiveData已变为普通变量,非reactive变量
      console.log("------updateObj---temp: ", temp); //{a: 1, b: 2}
    }

    function updateAttr() {
      temp.b = 10;
    }

    function updateData() {
      temp.a = 10;
    }

    return { temp, updateObj, updateAttr, updateData };
  },
};
</script>

<style lang="less" scoped>
.button {
  width: 200px;
  text-align: center;
  padding: 10px 5px;
  margin: 30px 0px;
  border: solid 1px #fff;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
}
</style>


//子组件
<template>
  <div>
    child: {{temp}}
  </div>
</template>

<script>

export default {
  name: "",
  props: {
    temp: {
      type: Object,
      required: true
    }
  },
}
</script>
  • 初始化

  • 上面例子中,如果点击1,再点击2、3,页面数据无变化
  • 直接点击2、3可看到数据变化,原因是点1触发的函数直接修改了变量的指向

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值