vue Keep-alive无法正常工作

时间:2018-04-25 10:28:03

标签: vue.js

我在vue-application中使用vue-router 虽然我设置了keep-alive,但每次刷新内容页面 每次我都会调用挂钩和激活的挂钩 在内容页面中 原谅我的英语很差 提前谢谢

//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
      ]
  }

2 个答案:

答案 0 :(得分:0)

我认为您需要在keep-alive元素中添加一个include =“ mycomponentname,mynextcomponetname,etc”属性。您还需要全局命名和注册这些组件。然后,您可以从路由中删除元数据,只需使路由按名称与组件匹配:

您的应用程序的根vue文件:

<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>

请在此处查看有关组件名称匹配的更多详细信息:

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

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

答案 1 :(得分:0)

在视图路由器上使用唯一键

        <keep-alive>
            <router-view v-if="$route.meta.keepAlive" :key="$route.fullPath"></router-view>
        </keep-alive>