Vue Router 的 keep-alive 和命名视图

在我的复古网页中想实现一个功能,用户点击一篇文章之后,返回文章列表不会被重新刷新

搜索了一下,可以通过 <keep-alive> 来实现

但问题就在于因为 文章列表 和 文章内容 渲染的地方都处于同一个 router-view

因此想通过命名视图来做到 文章列表 与 文章内容 分别渲染,同时通过 <keep-alive> 保留文章列表的内容

在上一篇文章 初步入门 Vue.JS 2 中有两个代码片段

在 JavaScript 中 routes 数组内两个对象中的 component 改为 components,并且使用括号包裹

像这样

main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const routes = [
{
path: '/',
components: {
getFeed
}
},
{
path: '/blog/:article',
components: {
readPost
}
}
]

接下来就可以在 HTML 中使用 named-views 了

把原来的 <router-view> 改成 <router-view name="COMPONENTS_NAME">

1
2
3
4
5
6
<div id="app">
<keep-alive>
<router-view name="getFeed"></router-view>
</keep-alive>
<router-view name="readPost"></router-view>
</div>

然后在渲染文章列表的地方用 <keep-alive> 包裹,就好惹