1. 程式人生 > 其它 >OO2022第三單元總結

OO2022第三單元總結

1.當被監視的屬性變化時,回撥函式自動呼叫,進行相關操作
2.監視的屬性必須存在,才能進行監視
3.自定義屬性和計算屬性都可以被監聽
深度監視:
(1)vue中的watch預設不檢測物件內部值的變化(一層)
(2)配置deep:true可以檢測物件內部值的改變(二層)
備註:
(1)vue自身可以檢測內部值的改變,但vue提供的watch預設不可以
(2)使用watch時根據資料的具體結構,決定是否採用深度檢測

<template>
    <div>
        <div>當前求和:{{sum}}</div>
        <button @click="sum++">點選+1</button>
    </div>
</template>
<script>
import { watch,ref, reactive } from 
'vue' export default { setup(){ let sum=ref(0) let msg=ref('你好,李煥英') let person=reactive({ name:'章三', age:18, job:{ j1:{ salary:'20K' } } }) //情況一:監聽ref所定義的一個響應式資料
watch(sum,(oldValue,newValue)=>{ console.log('監聽到了改變',oldValue,newValue); }) //情況二:監聽ref所定義的多個響應式資料 watch([sum,msg],(newValue,oldValue)=>{ console.log('sum or msg 變化了',newValue,oldValue); }) //情況三:監聽reactive所定義的一個響應式資料,注意,此處無法正確的展示舊value
watch(person.value,(newValue,oldValue)=>{ console.log('person變化了',newValue,oldValue); }) //情況四:監聽reactive所定義的一個響應式資料中的某個屬性 watch(()=>person.name,(newValue,oldValue)=>{ console.log('person的name變化了',newValue,oldValue); }) //情況五:監聽reactive所定義的一個響應式資料中的某些屬性 watch([()=>person.name,()=>person.age],(newValue,oldValue)=>{ console.log('person的name和age變化了',newValue,oldValue); }) return { sum, msg, person } } } </script>

用監視屬性完成計算屬性的案例->名字拼接

<template>
    <div>
        <h1>一個人的資訊</h1>
        姓:<input type="text" v-model="firstName" />
        <br>
        名:<input type="text" v-model="lastName" />
        <br>
        全名:<span>{{fullName}}</span>
        <br>
        修改:<input type="text" v-model="fullName" />
    </div>
</template>
<script setup>
import { watch,ref} from 'vue'
    let firstName=ref('張')
    let lastName=ref('三')
    let fullName=ref('張-三')
    watch(firstName,(newValue,oldValue)=>{
        setTimeout(()=>{
        fullName.value=newValue+'-'+lastName.value
        },1000)

    })
    watch(lastName,(newValue,oldValue)=>{
        fullName.value=firstName.value+'-'+newValue

    })
</script>

computed和watch之間的區別:
1.computed能完成的功能,watch都可以完成
2.watch能完成的功能,computed不一定能完成,例如:watch可以進行非同步操作
vue2中兩個有關this重要的小原則
1.所有被vue管理的函式,最好寫成普通函式,這樣this的指向才是vm或元件例項物件
2.所有不被vue所管理的函式(定時器的回撥、ajax的回撥函式,promise回撥函式等),最好寫成箭頭函式,這樣this的指向才是vm或元件例項物件