keep-alive 的使用

App.vue

<template>
  <router-view v-slot="{ Component }">
    <keep-alive :include="includeList">
      <component :is="Component" />
    </keep-alive>
  </router-view>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue-demi'
import { useRoute } from 'vue-router'

const includeList = ref<string[]>([])
const route = useRoute()
// const router = useRouter()
watch(
  () => route,
  (newVal: any, oldVal: any) => {
    const { name } = newVal
    if (newVal.meta.keepAlive && includeList.value.indexOf(name) === -1) {
      includeList.value.push(name)
    }
  },
  { deep: true }
) // 开启深度监听
</script>

<style lang="scss" scoped>
</style>

 2. 路由配置 meta 的 keepAlive 属性

 meta: { 
      keepAlive: true
  }

 3.路由守卫 让页面滚到顶部

router.afterEach((to) => {
  if (!to.meta?.keepAlive) {
    window.scrollTo(0, 0)
  }
})

  

posted @ 2022-07-07 16:40  福超  阅读(180)  评论(0编辑  收藏  举报