ref和reactive
- reactive在修改响应式对象的时候,要用Object.assign(car,{brand: 'xiaomi' , price : 20})
- 需要一个基本类型的响应式数据,必须使用ref
- 需要响应式对象,且层级不深,ref,reactive都可以
- 需要一个响应式对象,层级较深,推荐用reactive
<template>
<div class="person">
<h2>{{ car.brand }}车的价格是:{{ car.price }}万元</h2>
<button @click="changeBrand">修改车的品牌</button>
<button @click="changePrice">修改车的价格</button>
<button @click="changeCar">修改车</button>
</div>
</template>
<script lang="ts" name="Person" setup>
import { ref, reactive } from 'vue'
let car = reactive({ brand: '奔驰', price: 100 })
function changeBrand(){
car.brand = '宝马'
}
function changePrice(){
car.price += 10
}
function changeCar(){
//car = {brand: '小米', price: 20}
Object.assign(car,{brand: '小米', price: 20})
}
</script>
<style scoped>
.person {
background-color: skyblue;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
button {
margin: 0 5px;
}
li {
font-size: 20px;
}
</style>