vue3 watch用法

1、监听路由变化

import { ref, watch } from "vue"
import { useRoute } from "vue-router"

<script setup>
const route = useRoute()
const showPage = ref(false)
watch(
    () => route.path,
    (val) => {
        if (val === "/") {
            showPage.value = false
        } else {
            showPage.value = true
        }
    }
)

</script>

2、watch在监听 ref 类型时

import { ref, watch } from "vue"
import { useRoute } from "vue-router"

<script setup>
const route = useRoute()
const showPage = ref(false)
watch(
    showPage, // 注意这里变化
    (val,old) => {
        console.log('val',val);
        console.log('old',old);
    }
)

</script>

3、watch在监听 reactive 类型时

import { ref,reactive, watch } from "vue"
import { useRoute } from "vue-router"

<script setup>
const route = useRoute()
const data = reactive({ nums:0 })
watch(
    () => data.nums, // 注意这里
    (val,old) => {
        console.log('val',val);
        console.log('old',old);
    }
)

</script>

4、开启深度监听和 immediate监听立即执行

import { ref,reactive, watch } from "vue"
import { useRoute } from "vue-router"

<script setup>
const route = useRoute()
const data = reactive({ nums:0 })
watch(
    () => data.nums, // 注意这里
    (val,old) => {
        console.log('val',val);
        console.log('old',old);
    },
    {
        deep:true, // 深度监听
        immediate:true // 立即执行
    }
)

</script>

猜你喜欢

转载自blog.csdn.net/u014678583/article/details/124092868