017、Vue3+TypeScript基礎,使用watch監視reactive物件,預設是開啟的深度監視,且無法關閉

像一棵海草海草海草發表於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、程式碼如下:

<template>
  <div class="person">
    <h1>情況二:監視【ref】定義的【基本型別】資料</h1>
    <h2>姓名:{{ person.name }}</h2>
    <h2>年齡:{{ person.age }}</h2>
    <button @click="changeName">修改名字</button>
    <button @click="changeAge">修改年齡</button>
    <button @click="changePerson">修改整個人</button>
    <hr>
    <h2>測試:{{ obj.a.b.c }}</h2>
    <button @click="changeObj">修改obj.a.b.c</button>
  </div>
</template>

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

let person = reactive({
  name: '張三',
  age: 18
})

let obj = reactive({
  a: {
    b: {
      c: 100
    }
  }
})

function changeName() {
  person.name = '李四';
}

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

function changePerson() {
  Object.assign(person, {name: '王五', age: 20});
}

function changeObj() {
  obj.a.b.c += 1;
}

// 監視person變化, deep:true表示深度監視,immediate:true表示立即執行
watch(person, (newVal, oldVal) => {
  console.log('person變化了,由', oldVal, '變為:', newVal);
}, {deep: true, immediate: true})

// 如果是監視的reactive物件,預設是開啟的深度監視,且無法關閉
watch(obj, (newVal, oldVal) => {
  console.log('obj變化了,由', oldVal, '變為:', newVal);
})

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

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

03、效果如下:

相關文章