020、Vue3+TypeScript基礎,使用watch監視物件資料時,監控多種屬性的修改

像一棵海草海草海草發表於2024-08-18

01、App.vue程式碼如下:

<template>
  <div class="app">
    <h2>{{ title }}</h2>
    <!--    使用了ref來獲取子元件的屬性-->
    <Person/>
  </div>
</template>

<script lang="ts" setup name="App">
// JS或TS
import Person from './view/Person.vue'
import {ref} from 'vue'

let title = ref('好好學習,天天向上')

</script>

<!--樣式 scoped表示僅本單元有效-->
<style scoped>
.app {
  background-color: #ddd;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px;
}
</style>

02、Person.vue程式碼如下:

<template>
  <div class="person">
    <h2>姓名:{{ person.name }}</h2>
    <h2>年齡:{{ person.age }}</h2>
    <h2>汽車:{{ person.car.c1 }} 、{{ person.car.c2 }}</h2>
    <button @click="changeName">修改名字</button>
    <button @click="changeAge">修改年齡</button>
    <button @click="changeC1">修改第一臺車</button>
    <button @click="changeC2">修改第二臺車</button>
    <button @click="changeCar">修改整個車</button>
  </div>
</template>

<script lang="ts" name="Person001" setup>
import {reactive, watch} from 'vue'

let person = reactive({
  name: '張三',
  age: 18,
  car: {
    c1: '寶馬',
    c2: '奧迪'
  }
})

function changeName() {
  person.name += '~'
}

function changeAge() {
  person.age += 1;
}

function changeC1() {
  person.car.c1 += '~'
}

function changeC2() {
  person.car.c2 += '~'
}

function changeCar() {
  person.car = {
    c1: '賓士',
    c2: '比亞迪'
  }
}

// 監控多種屬性的修改
watch([() => person.name, () =>person.car], (oldValue, onCleanup) => {
  console.log('car變了:原:', oldValue, '現在:', onCleanup)
}, {deep: true})

</script>
<style scoped>
.person {
  background-color: #ddd;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px;

  button {
    margin: 0 5px;
  }
}
</style>

3、效果如下:

相關文章