vue Keep-alive not working

2019-08-01 15:26发布

i use vue-router in my vue-application content page refresh every time though i set keep-alive the mounted hook and activated hook has been called each time i e nter the content page Forgive me for my poor English
thanks in advance

//home.vue
    <div id="home">
        <topnav ref="childMethod"></topnav>
        <div class="mobile_header" ref="mobile_header"><img src="../assets/img/menu.png" @click="nav()"><p>earnest的小站</p></div>
        <keep-alive>
            <router-view v-if="$route.meta.keepAlive"></router-view>
        </keep-alive>
        <router-view v-if="!$route.meta.keepAlive"></router-view>
        <div id="iconfont1" @click="gotop1()" v-show="show" title="回到顶部"></div>
        <myfooter></myfooter>
    </div>


 //app.vue
<div id="app">
        <!-- 不管写没写跟路由都在APP。vue里面?一定要加上这一句 -->
        <loading v-show="isloading"></loading>
            <router-view></router-view>
</div>

//router index.js

const router=new Router({
    mode:'history',
    routes: [
    {
        path: '/',
        redirect:'/content',
        component: home,
        children:[
      //注意这里有逗号
      // 要是hash路由,这里无论点那个路由都是跳转到content
      {path:'/about', name:'about', component:about,meta:{keepAlive:true}},
      {path:'/archives',name:'archives',component:archives,meta:{keepAlive:true}},
      {path:'/content',name:'content',component:content,meta:{keepAlive:true}},
      {path:'/article:_id',name:'article',component:article,meta:{keepAlive:true}}//这里的name是命名路由里面的参数name
      ]
  }

标签: vue.js
1条回答
【Aperson】
2楼-- · 2019-08-01 15:40

I think you need to add an include="mycomponentname,mynextcomponetname,etc" attribute to your keep-alive element. You also need to have these components named and registered globally. Then you can remove the metadata from the route and just have the route match the component by name:

the root vue file for your application:

<template>
  <div id="app">
    <main role="main">
      <keep-alive include="somecomponent">
        <router-view class="view"></router-view>
      </keep-alive>
    </main>
  </div>
</template>

<script>    
  include SomeComponent from "../path/to/some-component"
  Vue.component("some-component", SomeComponent)
</script>

Have a look here for more details on the matching of component names:

vue forum: keep-alive not working with vue-router

Child Routes, keep-alive and nested keep-alive destroy considerations

查看更多
登录 后发表回答