如何分别使用不同的参数使 vue-router 保持活动状态?
电话:DR:
让我们考虑一个例子,当我们正在开发一个像 facebook 这样的网站时。每个用户都有一个个人资料页面。因为有很多用户,我们不想迭代所有用户并在加载时加载所有个人资料页面,如下所示
<template v-for="profile in profilePages">
<profile-page :data="profile" v-show="this.route.params['id'] === channel.id"/>
</template>
Run Code Online (Sandbox Code Playgroud)
常见的方法是:
路由器.js:
{
component: ProfileWrapper,
path: '/profile',
children: [
{
path: ':id',
component: ProfilePage
}
]
}
Run Code Online (Sandbox Code Playgroud)
频道页面:
<keep-alive>
<router-view :=key="$route.fullPath"></router-view>
</keep-alive>
Run Code Online (Sandbox Code Playgroud)
但问题就在这里。由于用户访问某人的页面并导航离开,我希望路由器将其保持在缓存中的某个地方,或者只是将其隐藏。在我的特殊情况下,用户最多访问 2-3 个配置文件并在它们之间切换很多。而且切换操作很费时间,因为里面有很多DOM。
我可以用vue-router和keep-alive来做吗?
编辑:
请检查沙箱。每次在页面(#1、#2、#3、#4)之间切换时,Vue都会ProfileInnerComponent从头开始创建新组件(而不是像 v-show 那样从缓存中创建)。通过检查红色 div 可以明显看出,调用了 的create钩子ProfileInnerComponent,它发出事件,并App添加具有当前时间的 div。
为了使其工作,您需要在组件上使用唯一的名称,然后您可以include在<keep-alive>.
<keep-alive include="Foo,Bar">
...
</keep-alive>
Run Code Online (Sandbox Code Playgroud)
在您的情况下,使用动态组件而不是单个路由会更好。
<component :is="$route.params.id"></component>
Run Code Online (Sandbox Code Playgroud)
更新
根据查询参数 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.
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6749 次 |
| 最近记录: |