vue单页应用,加入分页后,点击到第二页的时候,进入某个详情页,然后点击浏览器后退按钮,并没有返回到第二页,而是返回到了首页,并且刷新了页面,此时用keepAlive解决

备注https://www.cnblogs.com/sysuhanyf/p/7454530.html 这个比我写的更详细,我只是保留下我的实际代码,方便以后查阅;

import Vue from 'vue';
import Router from 'vue-router';
import CompanyList from '@/views/Company/List';
import CompanyDetail from '@/views/Company/Detail';
import ExpertList from '@/views/Expert/List';
import ExpertDetail from '@/views/Expert/Detail';
import ServiceBussiness from '@/views/Service/Bussiness';
import ServiceEngineer from '@/views/Service/Engineer';
import ServiceProduction from '@/views/Service/Production';
import ServiceTechnology from '@/views/Service/Technology';

Vue.use(Router);

const company = {
  template: `
    <div class="conpany">
    <!-- <router-view> --> //原来没有加keepAlive的写法
    **<keep-alive color="red">
      <router-view v-if="$route.meta.keepAlive"></router-view>
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive"></router-view>**
    </div>
  `
};
const expert = {
  template: `
    <div class="expert">
    **<keep-alive>
      <router-view v-if="$route.meta.keepAlive"></router-view>
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive"></router-view>**
    </div>
  `
};

const serviceS = {
  template: `
    <div class="service">
      <router-view/>
    </div>
  `
};

export default new Router({
  routes: [
    {
      path: '/',
      redirect: '/expert/list',
    },
    {
      path: '/company',
      component: company,
      children: [
        {
          path: 'list',
          name: 'list',
          component: CompanyList,
          **meta: { // 加了keepAlive后新增的
            keepAlive: true
          }**
        },
        {
          path: 'detail/:id',
          name: 'detail',
          component: CompanyDetail
        }
      ]
    },
    {
      path: '/expert',
      name: 'expertList',
      component: expert,
      children: [
        {
          path: 'list',
          name: 'list',
          component: ExpertList,
          meta: {
            keepAlive: true
          }
        },
        {
          path: 'detail/:id',
          name: 'expertDetail',
          component: ExpertDetail
        }
      ]
    },
    {
      path: '/service',
      component: serviceS,
      children: [
        {
          path: 'bussiness',
          name: 'list',
          component: ServiceBussiness
        },
        {
          path: 'engineer',
          name: 'engineer',
          component: ServiceEngineer
        },
        {
          path: 'production',
          name: 'production',
          component: ServiceProduction
        },
        {
          path: 'technology',
          name: 'technology',
          component: ServiceTechnology
        }
      ]
    }
  ]
});

给列表加了keepAlive ,这样点击某一页的时候,进入详情页,按后退按钮,返回的是该页

猜你喜欢

转载自blog.csdn.net/jo_an_na/article/details/81939756