vue3 keepAlive+记录滚动条

store

javascript 复制代码
import { defineStore } from 'pinia'

export const useCachedViewsStore = defineStore('cachedViews', {
    state: () => ({
        // 存储的是组件的 name,不是路由 path
        cachedViews: [] as string[]
    }),

    actions: {
        /** 添加缓存(路由守卫中调用) */
        addCachedView(name: string) {
            if (name && !this.cachedViews.includes(name)) {
                this.cachedViews.push(name)
            }
        },

        /** 移除指定缓存(关闭标签页/编辑后返回时调用) */
        removeCachedView(name: string) {
            const index = this.cachedViews.indexOf(name)
            if (index > -1) {
                this.cachedViews.splice(index, 1)
            }
        },

        /** 清空所有缓存(退出登录时调用) */
        clearAllCachedViews() {
            this.cachedViews = []
        }
    }
})

App.vue

javascript 复制代码
<template>
    <router-view v-slot="{ Component, route }">
        <keep-alive :include="cachedViews">
            <component :is="Component" :key="route.fullPath"/>
        </keep-alive>
    </router-view>
</template>

<script setup lang="ts">
    import {computed} from 'vue'
    import {useCachedViewsStore} from '@/store'

    const cachedViewsStore = useCachedViewsStore()
    const cachedViews = computed(() => cachedViewsStore.cachedViews)
</script>

router

javascript 复制代码
import {createRouter, createWebHashHistory} from 'vue-router'
import routes from './routes'
import {useCachedViewsStore} from '@/store'

const asmnPosition = {}
const router = createRouter({
    history: createWebHashHistory(`/#/${import.meta.env.VITE_PROJECT_NAME}/`),
    routes,
    scrollBehavior(to, from, savedPosition) {
        if (needKeepAlive(to)) {
            // savedPosition 是浏览器前进/后退时记录的位置
            if (savedPosition) {
                return savedPosition
            }
            // 代码 push 跳转,读取 asmnPosition 中保存的位置
            const top = asmnPosition[to.name]
            if (top)
                return {top}
        }
        // 滚动到顶部
        return {top: 0}
    }
})

router.beforeEach((to, from, next) => {
    const cachedViewsStore = useCachedViewsStore()
    if (needKeepAlive(to))
    // 注意:这里传入的是路由 name,必须和组件 name 保持一致!
        cachedViewsStore.addCachedView(to.name)

    if (needKeepAlive(from))
        asmnPosition[from.name] = window.scrollY

    next()
})


function needKeepAlive(to) {
    return to.meta.keepAlive && to.name
}

export default router

router

javascript 复制代码
const routes = [
    {
        path: '/',
        // keepAlive时name必须和组件 name 保持一致!
        name: 'home',
        component: () => import( '@/views/Home.vue'),
        meta: {
            keepAlive: true,
        }
    },
    {
        path: '/test',
        name: 'test',
        component: () => import( '@/views/Test.vue'),
    },
]

export default routes

home.vue

javascript 复制代码
<template>
    <div class="flex-center">
        <div class="a">
            <div class="b">slave-home</div>
        </div>
        <router-link to="/test">测试页</router-link>
        <div v-for="(v, i) in 100">
            {{v}}
        </div>
    </div>

    <HomeTabbar/>
</template>

<script setup lang="ts">
    import {ref} from 'vue'
    import HomeTabbar from '@/components/HomeTabbar/Index.vue'

		// 定义当前组件的name,同vue2的name
    defineOptions({
        name: 'home'
    })

    const active = ref('0')

    console.log('asmn')
</script>

<style lang="scss" scoped>
    .a {
        .b {
            color: red;
        }
    }
</style>

通过来回切换页面 Home --> Test ---> Home,看有无日志"asmn"输出,判断keepAlive是否生效,相当于有输出代表生效,即页面内的组件在test -> push -> Home回来的时候没被销毁。

keepAlive无法记录滚动条,所以也单独处理了,可观察切换回来时,滚动条是否与上次一致。

注意:使用keepAlive与记录滚动条,router里面的name需要与组件的name保持一致

相关推荐
翼帆10 分钟前
我用 AI 复刻了 CodeTank,重温代码坦克
前端·javascript·开源·ai编程·游戏开发·codetank
有趣的老凌13 分钟前
学习MarkDown笔记
前端
掘金者阿豪29 分钟前
数据库选型到底应该看什么?从业务需求到技术架构的实践分析
前端·后端
徐小夕2 小时前
万字拆解:零向量库、无模型微调,SAG2 凭什么刷新多跳问答 SOTA
前端·vue.js·github
黑土豆2 小时前
用 drawink 给业务页面加一层画板:从网页批注到无限板书
前端·javascript·github
恋猫de小郭2 小时前
Flutter 3.50.0 Release 的第一个崩溃,修好了,还没 hotfix
android·前端·flutter
IT_陈寒16 小时前
Redis那个过期删除策略,差点让我线上崩了
前端·人工智能·后端
jianqiang.xue17 小时前
Espressif-IDE进入维护模式:乐鑫把ESP32开发的宝押给VS Code
前端·css·ide
特创数字科技17 小时前
纯本地离线运行的文档脱敏工具(技术分享)
前端·驱动开发·python
心之语歌17 小时前
uni-app uts原生插件开发:uts 与 Kotlin 交互踩坑实录(附解决方案)
前端·后端