Vue Study

【Vue】ref与reactive

2023-12-25  本文已影响0人  Merbng

使用原则:

<template>
  <div class="person">
 <h2>当前求和为:{{ sum }}</h2>
    <button @click="changeSum">点我sum+1</button> 
    <h2>一辆{{ car.brand }}车,价值:{{ car.price }}w</h2>
    <button @click="changePrice">修改价格</button>
    <button @click="changeCar">修改汽车</button>
  </div>
</template>

/* <script lang="ts">
import { ref, reactive } from "vue";
export default {
  name: "Person", 
};
</script> */
<script lang="ts" setup name="Person24">

 let sum =ref(0)
 function changeSum(){
  sum.value+=1
  // 这样也是不行的
  sum =ref(8)
 }

let car = reactive({ brand: "奔驰", price: 100 });
// let car = ref({ brand: "奔驰", price: 100 }); 
function changePrice() {
  car.price += 10;
}
function changeCar(){
  // 无效 ,页面不会更新
  // car= {brand:'雅迪',price:0.1}
  // car = reactive({ brand: "奔驰", price: 100 });
  // 这个写法,页面可以更新
   Object.assign(car,{brand:'雅迪',price:0.1})
  //  ref 创建的变量必须使用.value (可以使用volar插件自动添加.value)
  // reactive 重新分配一个新对象,会失去响应式(可以使用Object.assign去整体替换)
  // 使用原则:
  // 1.如果只需要一个基本类型的数据,必须使用ref
  // 2.如果需要一个响应式对象,层级不深,ref,reactive都可以
  // 3.如果需要一个响应式对象,且层级较深,推荐使用reactive
}
</script>
<style>
.person {
  background-color: skyblue;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px;
} 
.button {
  margin: 0 5px;
} 
</style>
上一篇 下一篇

猜你喜欢

热点阅读