9.2. 添加活跃用户
简介
本小节中,我们将使用 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...