vue移动端列表页缓存不刷新

背景

在移动端列表页中,上拉加载更多。当点击某一条li标签进入详情页,再返回时由于vue的特性,会从新加载列表页,就会致使刚刚查看列表内容的进度。为了解决这个问题,能够查用keep-alive。vue

App.vue代码

<template>
  <div id="app">
    <keep-alive>
      <router-view v-if="$route.meta.keepAlive"></router-view>
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive"></router-view>
  </div>
</template>
<script>
export default {
  name: "App",
  mounted() {}
};
</script>
复制代码

main.js部分代码

router.beforeEach((to, from, next) => {
  /* 路由发生变化修改页面title */
  if (to.meta.title) {
    document.title = to.meta.title
  }
  /* 从列表页进入详情页则缓存列表页,若从其余页面进入列表页则不缓存列表页。 */
  if (from.meta.cacheTo) {
    from.meta.cacheTo.forEach(item => {
      if (item.includes(to.name)) {
        from.meta.keepAlive = true
      } else if (!item.includes(to.name)) {
        from.meta.keepAlive = false
      }
    })
  }
  next()
})
复制代码

router.js部分代码

{
    path: '/',
    name: 'home',
    component: () => import('@/views/home/index'),
    meta: {
      title: '首页'
    }
  },
  {
    path: '/detail',
    name: 'detail',
    component: () => import('@/views/list/detail'),
    meta: {
      title: '详情页'
    }
  },
  {
    path: '/list',
    name: 'list',
    component: () => import('@/views/list/index'),
    meta: {
      title: '列表页',
      cacheTo: ["detail"], //只有从本路由进入这个数组里的路由才会缓存list这个页面
      keepAlive: true
    },
  }
复制代码
mode: 'history', // require service support
// scrollBehavior: () => ({ y: 0 }),
scrollBehavior (to, from, savedPosition) {
if (savedPosition) {
  return savedPosition
} else {
  return { x: 0, y: 0 }
  }
},
base: process.env.NODE_ENV === 'development' ? '/' : '/app',
复制代码

结语

目前能够解决返回刷新的问题。若有问题,再更正。数组

相关文章
相关标签/搜索