watch函数:监听数据的变化
使用watch监听一个响应式数据
const count = ref(0);
watch(数据, 改变后回调函数)
watch(count, () => { console.log("count改变了"); });
使用watch监听多个响应式数据
const count = ref(0);
const user = ref('zs')
watch([数据1, 数据2, ...], 改变后回调函数)
watch([count, user], () => { console.log("数据改变了"); });
使用watch监听响应式对象数据中的一个属性(对象中的简单类型)
const user = reactive({ name: "tom", info: { gender: "男", age: 18, } });
watch(()=>数据, 改变后回调函数)
watch(()=>user.name, () => { console.log("数据改变了"); });
使用watch监听响应式对象数据中的一个属性(对象中的复杂类型),配置深度监听
const user = reactive({ name: "tom", info: { gender: "男", age: 18, } });
watch(()=>数据, 改变后回调函数, {deep: true})
watch(
() => user.info,
() => {
console.log("数据改变了");
},
{ // 开启深度监听 deep: true, } );
使用watch监听,配置默认执行
const user = reactive({ name: "tom", info: { gender: "男", age: 18, } });
watch(()=>数据, 改变后回调函数, {deep: true})
watch(
() => user.info,
() => {
console.log("数据改变了");
},
{
// 开启深度监听 deep: true,
// 默认执行一次 immediate: true
} );
Vue3和vue2的生命周期对比
选项式API下的生命周期函数使用 | 组合式API下的生命周期函数使用 |
---|---|
beforeCreate | 不需要(直接写到setup函数中) |
created | 不需要(直接写到setup函数中) |
beforeMount | onBeforeMount |
mounted | onMounted |
beforeUpdate | onBeforeUpdate |
updated | onUpdated |
beforeDestroyed | onBeforeUnmount |
destroyed | onUnmounted |
activated | onActivated |
deactivated | onDeactivated |
<script setup>
import { onMounted } from "vue";
// 生命周期函数:组件渲染完毕
onMounted(()=>{
console.log('onMounted触发了')
})
onMounted(()=>{
console.log('onMounted也触发了')
})
</script>
<template>
<div>生命周期函数</div>
</template>
如图:可以发现vue3周期函数的特点
1.以on开头
2.函数内容是一个回调函数
3.可以调用多次