Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue router use keep-alive to cache certain components?

I have started working with vue recently, and I have managed to create some simple pages, but I have noticed that the component once loaded are not cached, therefore for example on link below (which is what I am working on) youtube videos take time to load, and if I click on any other link and come back to videos they are loaded again.

Is it possible to use to cache components? preferably all of them instead of 1 by 1.

Here's my 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()
    }
});

View:

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

My app:

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

like image 684
Przemek Avatar asked Nov 29 '17 19:11

Przemek


1 Answers

Check this answer here: https://forum.vuejs.org/t/keep-alive-specific-component/2372/2

Since v2.1 You can use "include" and "exclude" attributes as regex for controlling which component will be cached. These attributes can also be v-bind'ed: https://v2.vuejs.org/v2/api/#keep-alive

Another way is by using the deactivated hook on the components you don't want to keep cached. In the hook, you call this.$destroy(); which removes the component under cache when it's not used.

Also, maybe this could help you? https://github.com/LinusBorg/portal-vue

Not sure if portal-vue would work, but my thinking is place the video outside so that it render independently (in a "portal" placed in the root component) and make it appear where you want using a "portal-target".

like image 143
Isometriq Avatar answered Nov 02 '22 11:11

Isometriq