vue3 ref 和reactive的区别

文章目录


源码分析视频 点击进入

Ref

ref数据响应式监听。ref 函数传入一个值作为参数,一般传入基本数据类型,返回一个基于该值的响应式Ref对象,该对象中的值一旦被改变和访问,都会被跟踪到,就像我们改写后的示例代码一样,通过修改 count.value 的值,可以触发模板的重新渲染,显示最新的值

<template>
  
  <h1>{{name}}</h1>
  <h1>{{age}}</h1>
  <button @click="sayName">按钮</button>
</template>

<script lang="ts">
import {ref,computed} from 'vue' 

export default {
  name: 'App',
  setup(){
    const name = ref('zhangsan')
    const birthYear = ref(2000)
    const now = ref(2020)
    const age = computed(()=>{
      return now.value - birthYear.value
    })
    const sayName = () =>{
      name.value = 'I am ' + name.value
    }
    return {
      name,
      sayName,
      age
    }
  }
}
</script>


reactive

reactive是用来定义更加复杂的数据类型,但是定义后里面的变量取出来就不在是响应式Ref对象数据了

所以需要用toRefs函数转化为响应式数据对象
在这里插入图片描述
将上面用ref写的代码转化成reactive型的代码

<template>
  <!-- <img alt="Vue logo" src="./assets/logo.png"> -->
  <div>
    <h1>{{ name }}</h1>
    <h1>{{ age }}</h1>
    <button @click="sayName">按钮</button>
  </div>
</template>

<script lang="ts">
import { computed, reactive,toRefs } from "vue";

interface DataProps {
  name: string;
  now: number;
  birthYear: number;
  age: number;
  sayName: () => void;
}

export default {
  name: "App",
  setup() {
   

    const data: DataProps = reactive({
      name: "zhangsan",
      birthYear: 2000,
      now: 2020,
      sayName: () => {
        console.log(1111);
        console.log(data.name);
        
        data.name = "I am " + data.name;
        console.log(data.name);
      },
      age: computed(() => {
        return data.now - data.birthYear;
      }),
    });

    const refData = toRefs(data)
    refData.age
    return {
      ...refData,
    };
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
  • 8
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值