9.2. 添加活跃用户

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

简介

本小节中,我们将使用 Mock.js 拦截请求并返回活跃用户,同时通过发起 Ajax 请求,来获取活跃用户。

模拟活跃用户

src/mock 下新建 index.js 文件,复制贴入以下代码:

src/mock/index.js

import Mock from 'mockjs'
import store from '../store'

// 拦截活跃用户请求并返回相关数据
Mock.mock('/users/active', 'get', () => {
  // 使用派生状态 computedArticles
  let articles = store.getters.computedArticles
  let comments = []
  let usersObj = {}
  // 活跃用户
  let activeUsers = []

  articles.map((article) => {
    const articleComments = Array.isArray(article.comments) ? article.comments : []
    // 合并评论,等价于 comments = comments.concat(articleComments)
    comments = [...comments, ...articleComments]
  })

  // 统计用户发布评论的数量,并返回包含头像和数量的对象
  usersObj = comments.reduce((accumulator, currentValue) => {
    accumulator[currentValue.uname] = accumulator[curre...

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

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

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

暂无话题~