通过关键参数使视图路由器保持活动状态 [英] Keep alive view-router by key param
问题描述
如何分别使用不同的参数使 vue-router 保持活动状态?
How do I keep vue-router alive with different params separately?
TL:DR:
让我们考虑一个例子,当我们正在开发一个像 facebook 这样的网站时.每个用户都有一个个人资料页面.因为有很多用户,我们不想迭代所有用户并加载所有个人资料页面,如下所示
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>
常见的方法是:
router.js:
{
component: ProfileWrapper,
path: '/profile',
children: [
{
path: ':id',
component: ProfilePage
}
]
}
频道页面:
<keep-alive>
<router-view :=key="$route.fullPath"></router-view>
</keep-alive>
但这就是问题所在.由于用户访问某人的页面并导航离开,我希望路由器将其保持在缓存中的某个地方,或者只是将其隐藏.在我的特殊情况下,用户最多访问 2-3 个配置文件并在它们之间切换很多.而且切换操作很费时间,因为里面有很多DOM.
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.
我可以使用 vue-router 和 keep-alive 来实现吗?
Can I do it with vue-router and keep-alive?
编辑:
请检查沙盒.每次在页面 (#1,#2,#3,#4) 之间切换时 Vue
从头开始创建新组件 ProfileInnerComponent
(而不是像 v-show 那样从缓存中).通过检查红色 div 可以明显看出,ProfileInnerComponent
的 create
钩子被调用,它发出事件,并且 App
添加带有当前时间的 div.
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.
推荐答案
为了使此功能正常工作,您需要在组件上使用唯一名称,然后您可以使用 < 上的
.include
属性;保持活动>
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>
更新
根据查询参数id预取频道内容:
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.
}
}
}
这篇关于通过关键参数使视图路由器保持活动状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!