---
# System prepended metadata

title: Watch練習

---

### ==第一種情況 - ref 基本型別監聽 + 結束監聽==
```javascript=
<template>
    {{ sum }}
    <button type="button" @click="sum += 1">增加</button>
</template>
<script>
    let sum = ref(0)
    const a = watch(sum, (newVal) => {
        console.log(newVal)
        if (newVal > 10) {
            a()
        }})        
</script>
```
### ==第二種情況 - ref 物件型別監聽==
```javascript=
<template>
    {{ person.name }}
    {{ person.age }}

    <button type="button" @click="person.name += '1'">增加名字</button>
    <button type="button" @click="person.age += 1">增加年齡</button>
    <button type="button" @click="person = { name: '柯基2號', age: 27 }">修改整個person</button>
</template>
<script>
    let person = ref({ name: '柯基', age: 25 })
    watch(
      () => person.value.name,
      (newVal, oldVal) => {
        console.log('改變', newVal, oldVal)
      }
    )      
</script>
```

### ==第三種情況 - reactive 監聽==
```javascript=
<template>
    
</template>
<script>
   
</script>
```
### ==第四種情況 - ref 或 reactive 物件型別中的某個屬性監聽，一律使用()=>，如果屬性是物件，可以搭配deep配置==
```javascript=
<template>
    {{ person2.name }}
    {{ person2.age }}
    {{ person2.like.a }}
    {{ person2.like.b }}

    <button type="button" @click="person2.name += '1'">修改名字</button>
    <button type="button" @click="person2.age += 1">修改年齡</button>
    <button type="button" @click="person2.like.a += '~'">修改like物件a</button>
    <button type="button" @click="person2.like.b += '+'">修改like物件b</button>
    <button type="button" @click="person2.like = { a: '葡萄', b: '芒果' }">改變like</button>
</template>
<script>
    let person2 = reactive({ name: '柯基', age: 23, like: { a: '蘋果', b: '香蕉' } })
watch(person2.like, (newVal, oldVal) => console.log(newVal, oldVal))
</script>
```
### ==第五種情況 - 多值監聽==
```javascript=
<template>
    {{ person3 }}
    <button type="button" @click="person3.name = '柯基二號'">改變名字</button>
    <button type="button" @click="person3.age -= 1">改變年齡</button>
</template>
<script>
    let person3 = ref({ name: '柯基', age: 25 })
    watch([() => person3.value.name, () => person3.value.age], (newVal, oldVal) => console.log(newVal, oldVal))      
</script>
```
  