ref 和 reactive

使用 ref 使变量响应式

在 Vue 3.0 中,我们可以通过一个新的 ref 函数使任何响应式变量在任何地方起作用,如下所示 :

import { ref } from 'vue'
const counter = ref(0)

ref 接收参数并将其包裹在一个带有 value property 的对象中返回,然后可以使用该 property 访问或更改响应式变量的值:

<template>
	<div>
		<button @click="count++">点击计数 : {{count}}</button>
	</div>
</template>
<script setup>
import {ref} from "Vue";
const count = ref(0);
</script>

ref 数据响应式修改

使用 变量.value = 来修改变量,即可实现变量的响应式修改 :

<template>
	<div>
		<button @click="counter">点击计数 : {{count}}</button>
	</div>
</template>
<script setup>
import {ref} from "Vue";
const count = ref(0);
const counter = ()=>{
	count.value ++;
}
</script>

使用 reactive 使引用型变量响应式

reactive 专门用来定义引用类型数据,实现修改变量时不需要再通过 value 同步数据,写法上操作更简单 ( 注意:reactive不能定义基本数据类型 )。

示例 :

<template>
	<div>
		<button @click="counter">点击计数 : {{count}}</button>
	</div>
	<div>
		{{user.name}}
	</div>
</template>
<script setup>
import {ref, reactive} from "Vue";
const count = ref(0);
const user  = reactive({
	name : "LessCode",
	age  : 10
});
const counter = ()=>{
	count.value ++;
	user.name = 'test';
}
</script>