keep-alive实现的简单实例

效果图:
keep-alive实现的简单实例

1、在App.vue页面

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/home">Home</router-link> |
      <router-link to="/about">About</router-link> |
      <router-link to="/news">News</router-link> |
      <router-link to="/my">My</router-link> 

    </div>
    <!-- <router-view /> -->

    <keep-alive>
        <router-view></router-view>
    </keep-alive>
  </div>
</template>

2、router文件夹的index.js

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import My from '../views/My.vue'
import News from '../views/news.vue'

import HomeNews from "../components/HomeNews.vue"
import HomeMsg from "../components/HomeMsg.vue"

Vue.use(VueRouter)

const routes = [
  {
    path:'',
    redirect:'/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta:{
      title:'首页'
    },
    children:[
      {
        path:'',
        redirect:'HomeNews'
      },
      {
        path:'HomeNews',
        name:'HomeNews',
        component:HomeNews,
        meta:{
          title:'新闻'
        },
      },
      {
        path:'HomeMsg',
        name:'HomeMsg',
        component:HomeMsg,
        meta:{
          title:'消息'
        },
      }
    ]
  },
  {
    path: '/about',
    name: 'About',
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue'),
    meta:{
      title:'关于'
    }
  },
  {
    path: '/my',
    name: 'My',
    component: My,
    meta:{
      title:'我的'
    }
  },
  {
    path: '/news',
    name: 'News',
    component: News,
    meta:{
      title:'新闻'
    }
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

  // 全局前置守卫,设置页面标题
router.beforeEach((to, from, next) => {
  // to and from are both route objects. must call `next`.
  // document.title = to.meta.title;
  document.title = to.matched[0].meta.title;
  console.log(to)
  next()
})

export default router

3、home.vue页面

<template>
  <div class="home">
    <h1>This is an Home page</h1>

    <router-link to="HomeNews">新闻</router-link> |
    <router-link to="HomeMsg">消息</router-link>

    <router-view></router-view>
  </div>
</template>

这时候,我们发现点击回到首页的时候,状态还是在新闻,并不是消息页。这是因为在路由页面中重定义了路由,需要删掉这个重定义配置。

但是删掉重定义配置后,第一页进入首页的时候,并不会显示新闻页。

这时,需要在home.vue页面设置
keep-alive实现的简单实例

到此,已经完成了。

上一篇:Http——Keep-Alive机制


下一篇:春招上岸总结贴,分享我的keep后端开发三次面试总结,希望对大家有帮助!