let xxx=ref(初始值)
import {ref} from ' vue '

<template>
<p>个人信息:</p>
<p>性别:{{ gender }}</p>
<p>年龄:{{ age }}</p>
<button @click="ageChange">点击年龄加1</button>
</template>
<script setup>
import { ref } from "vue";
// 数据
let gender = ref("女");
let age = ref(25);
// 方法
function ageChange() {
age.value += 1;
}
</script>
结果:

点击按钮,响应式数据会在页面上发生变化:

ref也可以创建对象类型的响应式数据。

修改ref的数据时记得.value的使用以及使用顺序:

在模板中,不需要使用.value

<template>
<p>小明的年龄是:{{ info.age }} 岁</p>
<p>小明的身高是:{{ info.height }} cm</p>
<button @click="ageChange">点击年龄加1</button>
<button @click="heightChange">点击身高加1</button>
<br />
<h2>星座列表:</h2>
<ul>
<li v-for="item in Constellation" :key="item.id">{{ item.star }}</li>
</ul>
<button @click="ConstellationChange">点击修改第二个星座名称</button>
</template>
<script setup>
import { ref } from "vue";
// 数据
let info = ref({
age: 20,
height: 165,
});
let Constellation = ref([
{ id: 1, star: "双子座" },
{ id: 2, star: "狮子座" },
{ id: 3, star: "巨蟹座" },
]);
// 方法
function ageChange() {
info.value.age += 1;
}
function heightChange() {
info.value.height += 1;
}
function ConstellationChange() {
Constellation.value[1].star = "处女座";
}
</script>
reactive只能定义对象类型的响应式数据,例如:
let info = reactive({
age: 20,
height: 165,
});
let Constellation = reactive([
{ id: 1, star: "双子座" },
{ id: 2, star: "狮子座" },
{ id: 3, star: "巨蟹座" },
]);
let name=reactive("张三")
<template>
<p>小明的年龄是:{{ info.age }} 岁</p>
<p>小明的身高是:{{ info.height }} cm</p>
<button @click="ageChange">点击年龄加1</button>
<button @click="heightChange">点击身高加1</button>
<br />
<h2>星座列表:</h2>
<ul>
<li v-for="item in Constellation" :key="item.id">{{ item.star }}</li>
</ul>
</template>
<script setup>
import { reactive } from "vue";
// 数据
let info = reactive({
age: 20,
height: 165,
});
let Constellation = reactive([
{ id: 1, star: "双子座" },
{ id: 2, star: "狮子座" },
{ id: 3, star: "巨蟹座" },
]);
// 方法
function ageChange() {
info.age += 1;
}
function heightChange() {
info.height += 1;
}
</script>
结果:

点击按钮,响应式数据会在页面上发生变化:

原本有数据如下:
// 数据
let info = reactive({
age: 20,
height: 165,
});
点击按钮对整体数据进行修改:
function infoChange() {
info={
age: 30,
height: 185,
}
}
但是这样修改数据之后,点击按钮数据并不会修改:

而使用object . assign可以让页面的数据进行更新:
function infoChange() {
Object.assign(info, {
age: 30,
height: 185,
});
}

结果如下:
