vue3首次加载时不触发 onActivated

361 阅读1分钟

实现思路

1.设置标志位:在组件的 data 中定义一个标志位,初始值为true

2.在onActivated 中检查标志位:在onActivated 钩子中检查标志位,如果为true ,则将其设置为false)并跳过后续逻辑;如果为false,则执行正常逻辑。

<template>
    <div>
    <1-组件内容 -->
    </div>
</template>
<script setup>
import { onActivated, ref } from 'vue';
// 定义一个标志位,初始值为 true
const isFirstLoad =ref(true);

onActivated(()=>{
    if(isFirstLoad.value){
    //如果是首次加载,将标志位设置为 false
        isFirstLoad.value = false;
        return;
    }
    // 非首次加载时执行的逻辑
    console.log('组件被激活');
});
</script>

来源:豆包