Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep alive view-router by key param

How do I keep vue-router alive with different params separately?

TL:DR:

Let's consider an example when we're developing a website like facebook. Each user has a profile page. Because there are a lot of users we don't want to iterate all users and load all profile page on load like bellow

<template v-for="profile in profilePages">
   <profile-page :data="profile" v-show="this.route.params['id'] === channel.id"/>
</template>

The common approach would be:

router.js:

{
  component: ProfileWrapper,
  path: '/profile',
  children: [
    {
      path: ':id',
      component: ProfilePage
    }
  ]
}

ChannelsPage:

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

But here's the issue. Since user visits someone's page and navigates away, I want the router to keep it alive in cache somewhere, or just hide it. In my particular case, user visits 2-3 profile at most and switches a lot between them. And switching operation is time costly, because there are a lot of DOM in it.

Can I do it with vue-router and keep-alive?

EDIT:

Please check the sandbox. Each time you switch between pages (#1,#2,#3,#4) Vue creates new components ProfileInnerComponent from the scratch (not from the cache like v-show). That's noticeably by checking red div, the create hook of ProfileInnerComponent is called, which emits the event, and App adds the div with current time.

like image 987
deathangel908 Avatar asked Jun 30 '18 17:06

deathangel908


Video Answer


2 Answers

In order this to work you need unique names on your components, which you would then use the include property on <keep-alive>.

<keep-alive include="Foo,Bar">
  ...
</keep-alive>

In you case, you would be better served using dynamic components rather than a single route.

<component :is="$route.params.id"></component>

keep-alive with Dynamic Components

keep-alive API reference

update

Pre-fetching channel content based on the query param id:

// routes.js
routes = [
  {
    path: '/channel/:id',
    name: 'show.channel',
    props: true,
    component: Channel
  }
  ...
]

// Channel.vue
import axios from 'axios'

export default {
  data () {
    return {
      content: ''
    }
  }
  beforeRouteEnter(to,from,next) {
    axios.get('/api/channel/' + to.params.id).then(response => {
      next(vm => {
        vm.content = reponse.data
      })
    })
  },
  watch: {
    '$route' (to, from) {
      // fetch new channel content when a query param is changed.
    }
  }
}
like image 119
Brian Lee Avatar answered Oct 19 '22 03:10

Brian Lee


I changed your sandbox by adding this codes:

// in App.vue

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

and

//in Profile.vue

  <keep-alive>
    <profile-inner-component v-for="i in comps" :key="i" :data="i"/>
  </keep-alive>
like image 33
Mohsen Avatar answered Oct 19 '22 01:10

Mohsen