Vue3中组合API中的侦听属性:watch
1.侦听一个数据
示例:
<script setup>
import{ref,watch} from 'vue'
const count = ref(0)
const setCount=()=>{
count.value++
}
//调用侦听工具(函数)
watch(count, ()=>{
console.log("侦听count,数据发生变化")
})
</script>
<template>
<button @click="setCount">{{ count }}</button>
</template>
2.侦听多个数据
示例:
<script setup>
import{ref,watch} from 'vue'
const count = ref(0)
const username = ref('小明')
const setCount=()=>{
count.value++
}
const setUsername=()=>{
username.value='小刘'
}
watch([count,username],([newCount,newUsername],[oldCount,oldUsername])=>{
console.log("count或username的值发生变化了",[newCount,newUsername],[oldCount,oldUsername])
})
</script>
<template>
<button @click="setCount">{{ count }}</button>
<button @click="setUsername">{{ username }}</button>
</template>
<style scoped>
</style>
3.深度侦听 默认情况属于浅层侦听,只能侦听至第一层,如果希望侦听对象里得到属性需要配置深度侦听。
示例:
<script setup>
import{ref,watch} from 'vue'
const state = ref(
{
count:0,
id:0,
name:'gaga'
})
const setState = ()=>{
state.value.count++
}
const setStateName = () =>{
state.value.name ='haha'
}
watch(state,()=>{
console.log("state的count发生变化了")
},{
deep:true
})
</script>
<template>
<button @click="setState">{{ state.count }}</button>
<button @click="setStateName">{{ state.name }}</button>
</template>
<style scoped>
</style>
4.精确侦听 如果对象中有多个属性,希望只侦听某一个属性需要配置精确侦听。
示例:
<script setup>
import{ref,watch} from 'vue'
const state = ref(
{
count:0,
id:0,
name:'xiaoming'
})
const setState = ()=>{
state.value.count++
}
const setStateName = () =>{
state.value.name ='daming'
}
watch(()=>state.value.count,()=>{
console.log("侦听了state对象的count属性")
})
</script>
<template>
<button @click="setState">{{ state.count }}</button>
<button @click="setStateName">{{ state.name }}</button>
</template>
<style scoped>
</style>
Vue3中组合API:生命周期函数(钩子函数)
组件从创造到销毁的过程称为生命周期,可以利用生命周期函数在创造或销毁过程中进行逻辑操作
setup onMounted加载时 onUnmounted组件卸载时 onBeforeUpdate更新前 onUpdate更新后
示例:
<script setup>
import { onMounted } from 'vue';
onMounted(()=>{
console.log("调用了onMounted函数1")
})
onMounted(()=>{
console.log("调用了onMounted函数2")
})
onMounted(()=>{
console.log("调用了onMounted函数3")
})
</script>
<template>
</template>
<style scoped>
</style>