0
点赞
收藏
分享

微信扫一扫

Vue3的组合式API - reactive和ref函数

组合式API - reactive和ref函数

1. reactive

接受对象类型数据的参数传入并返回一个响应式的对象

<script setup>
 // 导入
 import { reactive } from 'vue'
 // 执行函数 传入参数 变量接收
 const state = reactive({
   msg:'this is msg'
 })
 const setSate = ()=>{
   // 修改数据更新视图
   state.msg = 'this is new msg'
 }
</script>

<template>
  {{ state.msg }}
  <button @click="setState">change msg</button>
</template>

2. ref

接收简单类型或者对象类型的数据传入并返回一个响应式的对象

<script setup>
 // 导入
 import { ref } from 'vue'
 // 执行函数 传入参数 变量接收
 const count = ref(0)
 const setCount = ()=>{
   // 修改数据更新视图必须加上.value
   count.value++
 }
</script>

<template>
  <button @click="setCount">{{count}}</button>
</template>

3. reactive 对比 ref
  1. 都是用来生成响应式数据
  2. 不同点
  1. reactive不能处理简单类型的数据
  2. ref参数类型支持更好,但是必须通过.value做访问修改
  3. ref函数内部的实现依赖于reactive函数
  1. 在实际工作中的推荐
  1. 推荐使用ref函数,减少记忆负担
举报

相关推荐

0 条评论