vue3:ref 实现 基本数据类型响应式,reactive:实现 对象类型响应式
<template>
<div class="person">
<h2>姓名:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">修改年龄</button>
<button @click="showTel">查看联系方式</button>
</div>
</template>
<script lang="ts" setup name="person234">
import { ref } from 'vue' //想让哪个数据是响应式的,就用ref包裹
// 定义数据
//ref()是一个函数,用来包裹数据,让数据变成响应式的
let name = ref('张三')
let age = ref(25)
let tel = '123-456-7890'
console.log(name)
// 定义方法
function changeName() {
name.value = '李四'
console.log(name)
}
function changeAge() {
age.value = 30
}
function showTel() {
alert(tel)
console.log(tel)
}
</script>
<style scoped>
.person {
background-color: rgb(25, 120, 109);
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
button {
margin: 10px;
}
</style>
ref() 包裹之后,name就变成了一个对象
<template>
<div class="person">
<h2>一辆{{ car.brand }}车,价值{{ car.price }}w</h2>
<button @click="changePrice">修改汽车价格</button>
<hr>
<h2>喜欢的游戏:</h2>
<ul>
<li v-for="g in games" :key="g.id">{{ g.name }}</li>
</ul>
<button @click="changeFirstgame">修改第一个游戏</button>
<hr>
<button @click="changeC">修改c的值:{{ obj.a.b.c }}</button>
</div>
</template>
<script lang="ts" setup name="Person">
import { reactive } from 'vue'
// 定义数据
//reactive()是一个函数,用来包裹对象数据,让其变成响应式的
let car1 = {brand: '宝马', price: 200 }
let car = reactive({ brand: '奔驰', price: 100 })
console.log(car1)
console.log(car)
let games = reactive([
{id: 1, name: '王者荣耀'},
{id: 2, name: '英雄联盟'},
{id: 3, name: '绝地求生'}
])
//不管c的值有多深的嵌套,只要是reactive包裹的,都是响应式的
let obj = reactive({
a: {
b: {
c: 10
}
}
})
// 定义方法
function changePrice() {
car.price += 10
}
function changeFirstgame() {
games[0].name = '植物大战僵尸'
}
function changeC() {
obj.a.b.c = 100
}
</script>
<style scoped>
.person {
background-color: rgb(25, 120, 109);
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
button {
margin: 10px;
}
li {
font-size: 20px;
}
</style>