vue3中 ref 和 reactive 声明动态变量的区别

文章探讨了Vue3中使用组合式API的ref和reactive创建响应式变量的差异。reactive对对象和数组有效,但无法动态修改基本类型如string、number和boolean。而ref则返回一个ref对象,其值需通过.value访问,在模板中可自动解包。作者总结道,选择使用ref更为方便。

首先在vue3中实现变量动态话是靠组合式api中的ref或者reactive

一.reactive有局限性:

1.仅对对象、数组类型有效,对string、unmber、boolean无效

<template>
  <div @click="changReactive">{{ numberRective }}{{ stringRective }}{{ booleanRective }}</div>
</template>

<script setup>
import {reactive} from 'vue'

const numberRective = reactive(9)
const stringRective = reactive('字符串')
const booleanRective = reactive(true)

console.log(numberRective,stringRective,booleanRective,'可以打印')

//动态修改就会出现报错
//   function changReactive(){
//     numberRective = 10
//     stringRective = '被改变的字符串'
//     booleanRective = false
//     console.log(numberRective,stringRective,booleanRective,'但是不能动态化无效')
//   }


</script>

2.使用reactive声明string unmber boolean 并动态修改会出现一下报错:

 

二.ref的包裹性:

1.ref返回的都是一个ref对象,对应的值要  .value  才能拿到

<template>
  <div>{{ firstRef }}</div>
</template>

<script setup>
import {ref} from 'vue'

const firstRef = ref(9)
console.log(firstRef,'打印的是一个ref对象')
console.log(firstRef.value,'打印9')
</script>

2.在模板中用{{ }}这个语法可以自动解包,不需要 .value

<template>
  <div>{{ firstRef }}</div>
</template>

<script setup>
import {ref} from 'vue'

const firstRef = ref(9)
</script>

个人总结:感觉那个顺眼就用哪个,干脆用ref算了

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值