Vue3_响应式数据的处理方式

目录

ref和reactive区别

让一个普通数据转换为响应式数据,有如下两种方式

  1. ref函数,更适合单个变量
    在script标签中操作ref响应式数据要通过.value
    在template中操作ref响应式数据则无需.value
  2. reactive函数 更适合对象
    在script和template标签中操作都是直接使用对象名.属性方式即可

测试

clike 复制代码
实现 + - 按钮,实现数字加1减1

code

clike 复制代码
<script setup>
import {ref,reactive} from 'vue'
let counter = ref(10)

let person = reactive({
  name:"",
  age:101
})


</script>
<template>
<div>
<button @click="counter++">+</button>
<span >{{counter}}</span>
<button @click="counter--">-</button>
<hr>
<button @click="person.age--">-</button>
{{person.age}}
<button @click="person.age++">+</button>


</div>
</template>
<style scoped>
</style>

toRef函数和ToRefs函数

toRef函数:将reactive响应式数据中的某个属性转换为ref响应式数据

toRefs函数:同时将reactive响应式数据中的多个属性转换为ref响应式数据

clike 复制代码
<script setup>
import {ref,reactive,toRef,toRefs} from 'vue'
let counter = ref(10)

let person = reactive({
  name:"",
  age:101
})

let p_age = toRef(person,'age')
let {name,age} = toRefs(person)


</script>
<template>
<div>
  
<button @click="counter++">+</button>
<span >{{counter}}</span>
<button @click="counter--">-</button>
<hr>
<button @click="person.age--">-</button>
{{person.age}}
<button @click="person.age++">+</button>

<hr>
{{p_age}}
<button @click="p_age++">+</button>

<hr>
{{age}}
<button @click="age++">+</button>


</div>
</template>
<style scoped>
</style>
相关推荐
ly76891 小时前
CSS 从入门到进阶:系统掌握现代网页样式与布局
前端·css
SWAGGY..1 小时前
【C++初阶】:(15)模板进阶--从非类型参数到模板特化与分离编译
java·服务器·前端
YHHLAI1 小时前
从「跑分」到「干活」:Benchmark 与 GPT 5.6 的两种叙事
大数据·前端·人工智能·react.js·前端框架
BigTopOne1 小时前
ArLiveLite 用到的 C++/JNI 技术点
前端
BigTopOne1 小时前
ArLiveLite 技术架构-Lite
前端
BigTopOne1 小时前
ArLiveLite-具体功能
前端
BigTopOne1 小时前
ArLiveLite -具体功能
前端
Sherotree1 小时前
理解 JWT:三段分别是什么
前端·ai·开源
BigTopOne1 小时前
ArLiveLite 用到的 FFmpeg API
前端
小弥儿1 小时前
GPT Image 2 提示词库,把散落的生图提示词变成工程资产
开发语言·javascript·gpt·学习