onActivated()生命周期不可用的替代方法
Q:为什么会出现onActivated()生命周期不可用的情况?
A:当keep-alive存在但是,无法使用router-view的时候,英文onActivated()的是前提是keep-alive和router-view同时存在。
如何场景复现
像这种情况,既想缓存页面,又想再次进入子页面或子组件的时候走keep-alive缓存,但是,还想调用子页面或子组件的方法。
eg.此处父组件调用子组件的sayHello()方法。
父组件
<template>
<div>
<button @click="getChild('wendu')">触发子组件方法wendu</button>
<button @click="getChild('shidu')">触发子组件方法shidu</button>
<el-dialog v-model="dialogVisible" title="title" width="80%" draggable style="background: #091b37 !important; padding:1px !important" :close-on-click-modal="false">
<transition>
<keep-alive>
<component :is="Child" ref="childRef" :key="b"> </component>
</keep-alive>
</transition>
</el-dialog>
</div>
</template>
<script setup>
import { ref, nextTick } from 'vue'
import Child from './components/wendu.vue'
const b = ref('')
const dialogVisible = ref(false)
// 定义与 ref 同名变量
const childRef = ref(null)
const getChild = (a) => {
dialogVisible.value = true
b.value = a
nextTick(() => {
if (childRef.value) {
console.log(childRef.value);
console.log(childRef.value.sayHello);
childRef.value.sayHello(a);
} else {
console.log("子组件尚未渲染");
}
})
}
</script>
子组件
<template>
<div>我是子组件</div>
<input type="text" v-model="inputValue">
</template>
<script setup>
import { ref, defineExpose } from 'vue'
// 第一步:定义子组件的方法
const sayHello = (value) => {
console.log(value)
}
// 第二部:暴露方法
defineExpose({
sayHello
})
</script>
不走缓存
此外,如果,每次进入页面不走缓存完全按照第一次进入页面访问的方法有两种。
第一种
component的可以每次都不同。每访问一次内存都会增加。
<component :is="Child" ref="childRef" :key="b" :key="new Date()"> </component>
第二种
使用硬刷新,在子页面,使用如下代码。会加载两次。
onMounted(() => {
// 检查 sessionStorage 中是否已存在刷新标记
if (!sessionStorage.getItem('hasRefreshed')) {
// 设置刷新标记
sessionStorage.setItem('hasRefreshed', 'true');
// 刷新页面
window.location.reload();
}
});
onUnmounted(() => {
sessionStorage.removeItem('hasRefreshed');
});