6.3. 显示发布的文章
简介
本小节中,我们将新建一个文章页面,来显示对应的文章。仓库的 articles
的数据结构如下,其中的 articleId
是唯一的,我们可以通过它来获取对应的文章:
[
{
"uid": 1,
"articleId": 1,
"title": "标题",
"content": "内容",
"date": "2018-04-05T10:04:29.389Z"
}
]
返回指定 ID 文章
打开 src/store/index.js
文件,添加 getters
(注释部分是涉及的修改):
src/store/index.js
.
.
.
// 添加 getters
const getters = {
getArticleById: (state) => (id) => {
let articles = state.articles
if (Array.isArray(articles)) {
articles = articles.filter(article => parseInt(id) === parseInt(article.articleId))
return articles.length ? articles[0] : null
} else {
return null
}
}
}
const store = new Vuex.Store({
state,
// 注册 getters
getters,
mutat...