vue3 reactive 和 ref

reactive 和 ref

  • reactive()
    1、 返回对象的响应式副本。
    2、 解构会导致数据是去响应化。
  • ref()
    1、 接受一个内部值并返回一个响应式且可变的 ref 对象。ref 对象具有指向内部值的单个 property .value
    2 、 参数接收 基础数据类型。 不支持对象!

区别在于:

ref

使用 **ref** 的时候取值需要加上 .value , 修改的时候也是需要加上.value
例如: 
let c = ref('this is ref')

console.log(c.value) // this is ref

let editC = () => c.value = 'edit c'

console.log(c.value) // edit c


reactive

使用 reactive 的时候取值就不需要加.value了

let c = reactive({name: 'this reactive'})

console.log(c.name) // this reactive

let editC = () => c.name = 'edit c'

console.log(c.name) // edit c

这时候你一定发现了什么。 那就是 把上边代码中的name 换成 value 是不是和ref就很相似了?
留一点儿问题自己去找答案吧。远比看文章记得牢!


(2021-07-19 17:31:58)
特别注意!!! 改变 reactive() 解构出来的数据, 视图不会更新, 但 当更新ref的数据时会更新 解构出来的数据对应的视图

详细如下(具体代码如下方代码):
1 点击 change ref 按钮 改变 c 的值,其视图更新。
2 此时再点击 change myjson --> name 按钮, 其值改变但视图不会更新。
3 这时候若再点击 chang ref 按钮, 不仅 ref 对应的视图更新, <p>{{ name }}</p>(解构reactive的数据)视图也会更新。

大家使用reactive解构的时候如果不需要更新视图,还是需要注意的。
不知道是BUG还是特意如此设定的。

<template>
  <div>
    <div>
      <button @click="changeName">change myjson --> name</button>
      <br />
      <p>{{ name }}</p>
    </div>
    <div>
      <button @click="cg">change ref</button>
      <br />
      {{c}}
    </div>
  </div>
</template>

<script>
import { reactive, toRef, ref } from "vue";
export default {
  name: "HelloWorld",
  setup(props) {
    let my = {
      name: "cc",
      age: 12,
      ah: ["yy", "pb"],
      jn: {
        js: 10,
        html: 10,
      },
    };

    let myjson = reactive(my)

    let { name } = myjson;  

    let c = ref('cc')

    return {
      name,
      c
    };
  },
  methods: {
    changeName(){
      this.name += 'v'
      console.log(this.name); 
      // ↑ output:  ccv  数据改变但视图并没有更新。 解构会使 reactive()失去响应

    },
    cg(){
      this.c += "c"
      console.log(this.c);
    }
  },
};
</script>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值