6.3. 显示发布的文章

本教程最新版为 2.6,当前版本已放弃维护,请阅读最新版本!

简介

本小节中,我们将新建一个文章页面,来显示对应的文章。仓库的 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...

本文章首发在 LearnKu.com 网站上。

为了保证课程的高品质,我们需要对课程进行收费。付费后 才能观看剩余内容。 购买

上一篇 下一篇
讨论数量: 2