【问题标题】:Vue router use keep-alive to cache certain components?Vue路由器使用keep-alive缓存某些组件?
【发布时间】:2018-05-13 14:49:28
【问题描述】:

我最近开始使用 vue,并设法创建了一些简单的页面,但我注意到组件一旦加载就不会被缓存,因此例如在下面的链接上(这是我正在处理的)youtube视频需要一些时间来加载,如果我点击任何其他链接并返回视频,它们会再次加载。

是否可以用来缓存组件?最好是全部,而不是一个一个一个。

这是我的 vue:

import VueRouter from 'vue-router';
import Create from '../components/homepage/create.vue';
import How from '../components/homepage/how.vue';
import About from '../components/homepage/about.vue';
import Youtube from '../components/homepage/youtube.vue';
import Navigation from '../components/homeNavigation.vue';
import Login from '../components/auth/login.vue';
import Register from '../components/auth/register.vue';


const routes = [
    { path: '/create', component: Create },
    { path: '/how', component: How },
    { path: '/about', component: About},
    { name: 'youtube', path: '/youtube', component: Youtube},
    { path: '/login', component: Login},
    { path: '/register', component: Register},
];

Vue.use(VueRouter);
Vue.component('navigation', Navigation);

const router = new VueRouter({
    routes,
});

new Vue({
    el: '#app',
    router,
    updated: function () {
        Pace.restart()
    },
    mounted: function() {
        Pace.restart()
    }
});

查看:

<div id="app">
        <navigation></navigation>
            <transition appear name="slide-fade" mode="in-out">
                <keep-alive include='youtube'>
                    <router-view></router-view>
                </keep-alive>
            </transition>
</div>

我的应用:

http://b2750916.ngrok.io/#/youtube

【问题讨论】:

  • 我不确定这会解决它,但我会尝试 v-once 指令
  • 您是否尝试过视频以外的其他内容(可能是“iframed”)。因为keep-alive应该缓存组件数据。但我所说的数据并不是指 YT 视频的... 有可能获得更多细节吗?比如 youtube 组件是做什么的?
  • 你的 Youtube 组件的 name 属性是否等于 'youtube'?stackoverflow.com/questions/43116616/…

标签: vue.js vuejs2 vue-component vue-router


【解决方案1】:

在此处查看此答案: https://forum.vuejs.org/t/keep-alive-specific-component/2372/2

从 v2.1 开始,您可以使用“包含”和“排除”属性作为正则表达式来控制将缓存哪个组件。这些属性也可以是 v-bind 的: https://vuejs.org/v2/api/#keep-alive

另一种方法是在您不想缓存的组件上使用deactivated 挂钩。在钩子中,您调用this.$destroy();,它会在未使用时将缓存下的组件删除。

另外,也许这对你有帮助? https://github.com/LinusBorg/portal-vue

不确定portal-vue 是否可行,但我的想法是将视频放在外面,以便它独立渲染(在根组件中的“门户”中)并使用“门户目标”使其出现在您想要的位置”。

【讨论】:

  • 用于激活/停用的钩子!
猜你喜欢
  • 2018-04-03
  • 2018-12-18
  • 2019-12-16
  • 2020-08-25
  • 2017-01-25
  • 2018-07-17
  • 2020-06-29
  • 1970-01-01
  • 2018-09-06
相关资源
最近更新 更多