ref对比reactive
ref创建的对象数据类型修改整个对象时,用对象名.value即可,相当于是创建了一个新的对象
而reactive需要用Object.assign(对项名,{新数据}),只是改变原来的值
<template>
<div class="person">
<h2>车辆信息:一辆{{car.brand}}车,价值{{car.price}}万</h2>
<button @click="changePrice">修改汽车的价格</button>
<button @click="changeName">修改汽车的品牌</button>
<button @click="changeCar">修改汽车</button>
<hr>
<h2>当前求和为:{{ sum }}</h2>
<button @click="changeSum">点我sum加一</button>
</div>
</template>
<script lang="ts" setup name="Person">
import { ref, reactive, toRefs, onMounted } from 'vue'
let car=ref({brand:'奔驰',price:100})
let sum=ref(0)
function changePrice(){
car.value.price+=10
}
function changeSum(){
sum.value++
}
function changeName(){
car.value.brand=' Audi'
}
function changeCar(){
//Object.assign(car,{brand:'宝马',price:150})
car.value={brand:'奥拓',price:1}
}
</script>
<style scoped>
.person {
background-color: skyblue;
box-shadow: 0 0 10px;
border-radius: 5px;
padding: 20px;
}
button{
margin: 0 5px;
}
</style>
浙公网安备 33010602011771号