vue3 ref()函数,reactive()函数,toRefs()函数 学习使用

本文旨在探讨Vue3中的ref、reactive和toRefs函数的使用,通过实例解析它们在数据双向绑定中的作用。重点指出ref函数不仅能用于基本类型,也可处理数组,而reactive对数组赋值时可能不更新视图,以及如何通过toRefs进行响应式属性的拆解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习目标:

vue3 +ts 实现数据双向绑定

学习内容:

使用ref()函数

在看很多别人的博客文档中说,ref函数传入的为基本数据类型,reactive函数传入的为引用类型,但是在实际运用时,用ref传入一个数组也是可以的,相反我假如直接用reactive传入数组,赋值以后他不会同步更新页面,,,,

<template>
  <div class="welcome">
    <div>选择一个玩具</div>
    <div> 
      <button v-for="(item,index) in list" :key="index" @click="handle(item)">{{index}}:{{item}}</button>
    </div>
    <div>你选择了{{checkitem}}玩具</div>
  </div>
</template>
<script lang="ts">
  import { defineComponent,ref } from 'vue';
  export default defineComponent({
    name: 'Welcome',
    setup(){
      const list=ref([
       "坦克",
       "手枪",
       "奥特曼"
      ])
      const checkitem=ref('')
      const handle=(item:string)=>{
          checkitem.value=item
      }
      return{
        list,
        checkitem,
        handle
      }
    }
  });
</script>
<style lang="less" scoped>
</style>

使用reactive()函数

<template>
    <div>
    <div>选择一个玩具</div>
    <div> 
    <button v-for="(item,index) in data.list" :key="index"  @click="data.handle(item)">{{item}}</button>
    </div>
    <div>你选择了{{data.checkitem}}玩具</div>
    </div>
</template>
<script lang='ts'>
import {defineComponent, reactive} from 'vue'
interface dataobj{//定义为接口类型,更加详细的定义对象里的每个属性值类型
  list:Array<any>,
  checkitem:String,
  handle:(item:string)=>void,//定义为函数类型,入参为字符串类型:无返参的普通函数
  [propName:string]:any,//该对象还可加入任意属性值类型
   };
export default defineComponent({
  name:'four',
  setup(){
  const data=reactive({
    list:[ "坦克","手枪","奥特曼"],
    checkitem:'',
    handle:(item:string)=>{
      data.checkitem=item
    } 
  }) as dataobj
   return{
     data //抛出一个对象,模板中用   对象.属性名  获取想要的属性值
   }
  }
})
</script>

<style>
</style>

使用toRefs()函数

<template>
    <div>
    <div>选择一个玩具</div>
    <div> 
    <button v-for="(item,index) in list" :key="index"  @click="handle(item)">{{item}}</button>
    </div>
    <div>你选择了{{checkitem}}玩具</div>
    </div>
</template>
<script lang='ts'>
import {defineComponent, reactive,toRefs} from 'vue'
interface dataobj{//定义为接口类型,更加详细的定义对象里的每个属性值类型
  list:Array<any>,
  checkitem:String,
  handle:(item:string)=>void,//定义为函数类型,入参为字符串类型:无返参的普通函数
  [propName:string]:any,//该对象还可加入任意属性值类型
   };
export default defineComponent({
  name:'four',
  setup(){
  const data=reactive({
    list:[ "坦克","手枪","奥特曼"],
    checkitem:'',
    handle:(item:string)=>{
      data.checkitem=item
    } 
  }) as dataobj
   return{
    ...toRefs(data) //抛出一个对象传入toRefs,将toRefs返回出的值将其解构后仍具有响应特性,视图不再用.属性名来获取值
   }
  }
})
</script>
<style>
</style>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值