组合式API - reactive和ref函数(Vue3学习5)
2023-11-19 本文已影响0人
扶得一人醉如苏沐晨
一、reactive()
![](https://img.haomeiwen.com/i27493437/3792b4fecb81c0fa.png)
<script setup>
import { reactive } from "vue";
const state = reactive({
count: 1,
});
const addCount = () => {
state.count++;
};
</script>
<template>
<h1>{{ state.count }}</h1>
<button @click="addCount">点我+1</button>
</template>
二、ref()
![](https://img.haomeiwen.com/i27493437/c3a88a1b3e5eac5c.png)
本质:是在原有传入数据的基础上,外层包了一层对象,包成了复杂类型
底层:包成复杂类型之后,再借助 reactive 实现的响应式
注意点:
- 脚本中访问数据,需要通过 .value
- 在template中,.value不需要加 (帮我们扒了一层)
推荐: 以后声明数据,统一用 ref => 统一了编码规范
<script setup>
import { ref } from "vue";
const count = ref(0);
const addCount = () => {
count.value++;
};
</script>
<template>
<h1>{{ count }}</h1>
<button @click="addCount">点我+1</button>
</template>
三、总结
![](https://img.haomeiwen.com/i27493437/a334f8560f248dc4.png)