iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >vue3ref和reactive的区别详解
  • 103
分享到

vue3ref和reactive的区别详解

vue3ref和reactive 2023-03-19 18:03:56 103人浏览 八月长安
摘要

目录RefReactive源码分析视频 点击进入 Ref ref数据响应式监听。ref 函数传入一个值作为参数,一般传入基本数据类型,返回一个基于该值的响应式Ref对象,该

源码分析视频 点击进入

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>

到此这篇关于vue3 ref 和reactive的区别详解的文章就介绍到这了,更多相关vue3 ref 和reactive 内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: vue3ref和reactive的区别详解

本文链接: https://www.lsjlt.com/news/200288.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作