vue3 ref和reactive的区别有哪些

发布时间:2023-03-17 10:16:35 作者:iii
来源:亿速云 阅读:90

本文小编为大家详细介绍“vue3 ref和reactive的区别有哪些”,内容详细,步骤清晰,细节处理妥当,希望这篇“vue3 ref和reactive的区别有哪些”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

Ref

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

<template>
  
  <h2>{{name}}</h2>
  <h2>{{age}}</h2>
  <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函数转化为响应式数据对象

vue3 ref和reactive的区别有哪些

将上面用ref写的代码转化成reactive型的代码

<template>
  <!-- <img alt="Vue logo" src="./assets/logo.png"> -->
  <div>
    <h2>{{ name }}</h2>
    <h2>{{ age }}</h2>
    <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的区别有哪些”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. vue3+electron12+dll开发客户端配置的示例分析
  2. vue3中如何使用setup、ref和reactive

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue3 ref reactive

上一篇:linux中stream的含义是什么

下一篇:MybatisPlus如何实现insertBatchSomeColumn进行批量增加

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》