How to GraphQL 实战(Vue.js + Apollo):实现投票 Mutation 并用命令式 Store API 更新缓存

原创2026-09-25 14:32:311,923 阅读

How to GraphQL 实战(Vue.js + Apollo):实现投票 Mutation 并用命令式 Store API 更新缓存

本篇技术指南围绕 howtographql 仓库中 Vue.js + Apollo 前端教程的核心章节展开:在 Hackernews 克隆应用中实现"为链接投票(Vote)"功能。文章会完整演示如何准备 Vue 组件、在 Graphcool 数据模型中新增 Vote 类型与关联关系、调用 createVote 变更操作,以及如何借助 Apollo Client 的命令式 Store API(readQuery / writeQuery)在 Mutation 完成后立即刷新缓存并驱动 UI 重渲染。读完本文,你将掌握"Mutation 执行后同步更新 Apollo 缓存"的完整套路,并理解其背后的数据流。

本教程对应仓库原始文档:content/frontend/vue-apollo/6-more-mutations-and-updating-the-store.md,属于 content/frontend/vue-apollo 系列(1~10 章)的第六步。前置内容为查询加载链接、createLink 变更与缓存更新、基于 Graphcool 的邮箱密码认证与 vue-router 路由,可参见 2-queries-loading-links.md、3-mutations-creating-links.md、5-authentication.md 与 4-routing.md。

功能目标:为链接投票

本小节要实现的下一项功能是投票(Voting):已登录用户可以为某条链接提交一个投票(Vote),得票最多的链接稍后会展示在单独的页面上(对应教程后续的 /top 路由,见 9-pagination.md)。

整个实现分四步走:

  1. 更新 Vue 组件,让每条链接渲染出投票数与发布者信息,并显示可点击的投票按钮;
  2. 更新 Graphcool 数据模型(schema),新增 Vote 类型及其与 User、Link 的双向关联;
  3. 在 allLinks 查询中补上 votes 字段,并在 src/constants/graphql.js 中定义 createVote 变更操作;
  4. 通过 Apollo 的命令式 Store API,在 Mutation 返回后立即更新缓存,使 UI 实时显示正确的票数。

准备 Vue 组件:LinkItem 渲染票数与投票按钮

第一步是改造 src/components/LinkItem.vue。该组件需要做到三件事:

  • 显示每条链接在列表中的序号(linkNumber);
  • 在用户已登录(存在 userId)时渲染一个向上的投票按钮(▲),点击触发 voteForLink();
  • 展示链接的票数(link.votes.length)与发布者名字(link.postedBy.name,无发布者时显示 Unknown)。

将 src/components/LinkItem.vue 更新为如下内容:

<template>
  <div class="flex mt2 items-start">
    <div class="flex items-center">
      <span class="gray">{{linkNumber}}.</span>
      <div v-if="userId" class="ml1 gray f11 upvote" @click="voteForLink()">▲</div>
    </div>
    <div class="ml1">
      <a :href="link.url" class="link">{{link.description}} ({{link.url}})</a>
      <div class="f6 lh-copy gray">
        {{link.votes.length}} votes | by {{link.postedBy ? link.postedBy.name : 'Unknown'}} {{timeDifferenceForDate(link.createdAt)}}
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'LinkItem',
    computed: {
      userId () {
        return this.$root.$data.userId
      },
      linkNumber () {
        if (this.$route.path.includes('new')) {
          return (this.pageNumber - 1) * this.linksPerPage + (this.index + 1)
        } else {
          return this.index + 1
        }
      }
    },
    props: ['link', 'index'],
    methods: {
      timeDifferenceForDate
    }
  }
</script>

<style scoped>
  .upvote {
    cursor: pointer;
  }

  .link {
    text-decoration: none;
    color: black;
  }
</style>

关键点解读:

  • userId 来源:this.$root.$data.userId。这是在认证章节里由根实例在 src/main.js 中初始化的(从 localStorage 读取 GC_USER_ID,见 5-authentication.md)。只有 userId 存在时,投票按钮才渲染,从而保证只有登录用户能投票。
  • linkNumber 计算:区分两种场景——在 /new 页面(分页列表)按"页码 × 每页条数 + 当前位置"计算全局序号;在其他页面直接使用 index + 1。这里用到的 pageNumber、linksPerPage 与 index 分别来自父组件传入的 props 和本组件 data,分页相关内容会在 9-pagination.md 中展开。
  • timeDifferenceForDate:把 createdAt 时间戳转成 "3 hours ago" 这类更友好的字符串,需要新建工具函数。

实现 timeDifferenceForDate 工具函数

在 src 目录下新建 utils 目录,并创建 src/utils/index.js:

function timeDifference (current, previous) {
  const milliSecondsPerMinute = 60 * 1000
  const milliSecondsPerHour = milliSecondsPerMinute * 60
  const milliSecondsPerDay = milliSecondsPerHour * 24
  const milliSecondsPerMonth = milliSecondsPerDay * 30
  const milliSecondsPerYear = milliSecondsPerDay * 365

  const elapsed = current - previous

  if (elapsed < milliSecondsPerMinute / 3) {
    return 'just now'
  }

  if (elapsed < milliSecondsPerMinute) {
    return 'less than 1 min ago'
  } else if (elapsed < milliSecondsPerHour) {
    return Math.round(elapsed / milliSecondsPerMinute) + ' min ago'
  } else if (elapsed < milliSecondsPerDay) {
    return Math.round(elapsed / milliSecondsPerHour) + ' h ago'
  } else if (elapsed < milliSecondsPerMonth) {
    return Math.round(elapsed / milliSecondsPerDay) + ' days ago'
  } else if (elapsed < milliSecondsPerYear) {
    return Math.round(elapsed / milliSecondsPerMonth) + ' mo ago'
  } else {
    return Math.round(elapsed / milliSecondsPerYear) + ' years ago'
  }
}

export function timeDifferenceForDate (date) {
  const now = new Date().getTime()
  const updated = new Date(date).getTime()
  return timeDifference(now, updated)
}

该函数以毫秒为单位计算时间差,按 20 秒、1 分钟、1 小时、1 天、1 个月、1 年的阈值逐级归类,返回 just now、less than 1 min ago、5 min ago、3 h ago、2 days ago、4 mo ago、1 years ago 等文本。随后回到 LinkItem.vue,在 script 块顶部导入它:

import { timeDifferenceForDate } from '../utils'

从 LinkList 传入索引

为了让每条链接能渲染自己在列表中的位置,父组件 src/components/LinkList.vue 需要在渲染 LinkItem 时把 index 传下去:

<link-item
  v-for="(link, index) in allLinks"
  :key="link.id"
  :link="link"
  :index="index">
</link-item>

此时应用暂时无法正常运行:查询里还没有 votes 字段,模板却已经引用了 link.votes.length。这正是下一步要解决的问题。

更新 Schema:新增 Vote 类型与双向关联

投票在数据模型中用自定义的 Vote 类型表示。打开项目根目录下的 project.graphcool 文件,添加如下类型:

type Vote @model{
  id: ID! @isUnique
  user: User! @relation(name: "UsersVotes")
  link: Link! @relation(name: "VotesOnLink")
}

每个 Vote 同时关联到创建它的 User 以及它所属的 Link。因此还要补上关联的另一端——在 User 类型中添加字段:

votes: [Vote!]! @relation(name: "UsersVotes")

在 Link 类型中添加字段:

votes: [Vote!]! @relation(name: "VotesOnLink")

完整后的数据模型与仓库中 meta/structure/vue-apollo.md 记录的最终 schema 一致:User 拥有 links 与 votes 两个列表字段,Link 拥有 postedBy 与 votes,Vote 则同时持有 user 和 link 引用。仓库另一份后端结构文档 meta/structure/express.md 也给出了等价的 SDL 定义,并补充了由该模型自动生成的 API 形态,例如 createVote(linkId: ID, userId: ID): Vote 变更以及 Vote(filter: VoteSubscriptionFilter): VoteSubscriptionPayload 订阅,说明服务端会基于关系模型自动暴露对应的 CRUD 操作。

应用 schema 变更:graphcool push

打开终端并进入 project.graphcool 所在目录,执行:

graphcool push

终端输出大致如下:

$ gc push
 ✔ Your schema was successfully updated. Here are the changes:

  | (+)  A new type with the name `Vote` is created.
  |
  | (+)  The relation `UsersVotes` is created. It connects the type `User` with the type `Vote`.
  |
  | (+)  The relation `VotesOnLink` is created. It connects the type `Link` with the type `Vote`.

Your project file project.graphcool was updated. Reload it in your editor if needed.

相关 CLI 提示:认证章节还提到 graphcool pull(把远端变更拉取到本地项目文件)与 graphcool status(预览 push 前将要发生的变更),参见 5-authentication.md。另外该教程使用 Graphcool 旧版(legacy)服务与 graphcool@0.4 版本 CLI,详见 1-getting-started.md 中的说明。

修复查询:在 allLinks 中带上投票信息

Schema 更新完成后,就可以修复刚才导致应用无法运行的问题——在 src/constants/graphql.js 中把 ALL_LINKS_QUERY 更新为同时包含发布者与投票信息:

export const ALL_LINKS_QUERY = gql`
  query AllLinksQuery {
    allLinks {
      id
      createdAt
      url
      description
      postedBy {
        id
        name
      }
      votes {
        id
        user {
          id
        }
      }
    }
  }
`

这里只是在查询的 payload 中追加了两部分:发布该链接的用户信息(postedBy)以及链接的投票信息(votes,其中每票只取 id 和投票者的 user.id,供前端判断当前用户是否已投过票)。此时重新运行应用,链接即可正常显示,每条链接旁边会出现投票数与发布者名字。

查询与变更统一维护在 src/constants/graphql.js,组件按需导入——这一约定在 2-queries-loading-links.md 中确立。

定义并调用 createVote Mutation

定义 CREATE_VOTE_MUTATION

继续在 src/constants/graphql.js 中追加投票变更操作:

export const CREATE_VOTE_MUTATION = gql`
  mutation CreateVoteMutation($userId: ID!, $linkId: ID!) {
    createVote(userId: $userId, linkId: $linkId) {
      id
      link {
        votes {
          id
          user {
            id
          }
        }
      }
      user {
        id
      }
    }
  }
`

CreateVoteMutation 接收 userId 与 linkId 两个必填参数。它的返回 payload 里嵌套了被投票链接的完整 votes 列表(每票含 id 与投票者 user.id),这正是下一步更新缓存时要用到的数据。对应到 meta/structure/express.md 中的服务端定义,createVote(linkId: ID, userId: ID): Vote 会返回一个 Vote 节点,其关系字段 user 与 link 均可嵌套查询。

在 LinkItem 中导入常量

在 src/components/LinkItem.vue 的 script 块顶部,导入刚定义的变更操作以及用于读取用户 ID 的常量:

import { CREATE_VOTE_MUTATION } from '../constants/graphql'
import { GC_USER_ID } from '../constants/settings'

其中 GC_USER_ID = 'graphcool-user-id' 是存储在浏览器 localStorage 中的键名,定义在 src/constants/settings.js(见 5-authentication.md)。

实现 voteForLink 方法

在 LinkItem.vue 中实现投票方法:

voteForLink () {
  const userId = localStorage.getItem(GC_USER_ID)
  const voterIds = this.link.votes.map(vote => vote.user.id)
  if (voterIds.includes(userId)) {
    alert(`User (${userId}) already voted for this link.`)
    return
  }
  const linkId = this.link.id
  this.$apollo.mutate({
    mutation: CREATE_VOTE_MUTATION,
    variables: {
      userId,
      linkId
    }
  })
}

方法前半段是去重保护:从 localStorage 取出当前用户 ID,把 this.link.votes 映射成投票者 ID 数组 voterIds,若其中已包含当前用户,就弹出提示并提前返回,不真正执行 Mutation。

测试一下:点击某条链接上的投票按钮,暂时看不到任何 UI 反馈,但刷新页面后就能看到票数增加。

⚠️ 当前的缺陷:由于 Link 上的 votes 不会在执行后立即更新,用户可以在刷新页面之前无限次投票。只有刷新后保护机制才生效——再次点击投票按钮不会产生新投票,只会在控制台输出类似 User (cj42qfzwnugfo01955uasit8l) already voted for this link. 的日志。这说明 Mutation 本身工作正常,接下来就修复该问题:让缓存(cache)在每次变更后立即更新。

更新缓存:Apollo 命令式 Store API

Apollo 的一个亮点是可以手动控制缓存内容。在 Mutation 执行后,这种方式尤其有用——你可以精确决定缓存应该如何更新。这里就用它来确保 createVote 变更一执行,UI 立即显示正确的票数。所用到的正是 Apollo Client 的命令式 Store API。

给 mutate 传入 update 回调

修改 LinkItem.vue 中 voteForLink 方法里的 mutate 调用:

this.$apollo.mutate({
  mutation: CREATE_VOTE_MUTATION,
  variables: {
    userId,
    linkId
  },
  update: (store, { data: { createVote } }) => {
    this.updateStoreAfterVote(store, createVote, linkId)
  }
})

update 函数会在服务器返回响应时被调用,它接收两个参数:

  • store:Apollo 当前的内存缓存(数据仓库);
  • data:变更的返回 payload——这里通过**解构(destructuring)**直接把 createVote 字段取了出来。

你可以利用这两个输入,为缓存计算出一个新状态。早在 CreateLink 组件中(3-mutations-creating-links.md 与 4-routing.md),我们就已经用同样的方式做过"变更后同步更新缓存"——update 中先 readQuery 读取 ALL_LINKS_QUERY,push 新链接,再 writeQuery 写回。现在投票场景只是换成了"替换某条链接的 votes"。

实现 updateStoreAfterVote

继续在 LinkItem.vue 中新增方法:

updateStoreAfterVote (store, createVote, linkId) {
  // 1
  const data = store.readQuery({
    query: ALL_LINKS_QUERY
  })

  // 2
  const votedLink = data.allLinks.find(link => link.id === linkId)
  votedLink.votes = createVote.link.votes

  // 3
  store.writeQuery({ query: ALL_LINKS_QUERY, data })
}

三步逻辑清晰明了:

  1. 读取:用 store.readQuery({ query: ALL_LINKS_QUERY }) 从缓存中读取 ALL_LINKS_QUERY 当前的查询结果(即当前缓存的全部链接列表)。
  2. 修改:在 data.allLinks 中通过 link.id === linkId 找到刚被投票的链接,然后把它的 votes 重置为服务器返回的 createVote.link.votes(这是包含新投票在内的最新列表)。
  3. 写回:用 store.writeQuery({ query: ALL_LINKS_QUERY, data }) 把修改后的数据写回缓存。

别忘了导入 ALL_LINKS_QUERY:

import { ALL_LINKS_QUERY, CREATE_VOTE_MUTATION } from '../constants/graphql'

缓存更新如何驱动 UI 重渲染

update 回调执行后,Store 得到正确更新,而 Store 的变更会触发组件重新渲染,UI 随即显示正确的票数——这就解决了上文提到的"可无限投票"缺陷:现在每次投票后缓存立即反映最新票数,voterIds 数组在下次点击时已经包含当前用户,去重保护即时生效。

需要说明两点工程细节:

  • 查询参数一致性:本例中 readQuery / writeQuery 与查询定义完全一致即可命中同一条缓存记录。在教程后续引入分页与排序后(9-pagination.md),ALL_LINKS_QUERY 会携带 first、skip、orderBy 变量,此时 updateStoreAfterVote 中的 readQuery / writeQuery 也必须带上完全相同的 variables 才能正确读写缓存。这说明命令式 Store API 以"查询文档 + 变量"作为缓存键。
  • 与订阅的配合:在 8-subscriptions.md 中,应用还会通过 subscribeToMore 订阅 NEW_VOTES_SUBSCRIPTION,用 Redux-reducer 式的 updateQuery 把他人投出的新票合并进缓存——两种方式(命令式更新与订阅更新)本质都是在操作同一份 Apollo 缓存。

小结

至此,投票功能完整闭环:组件层(LinkItem 渲染票数/按钮、timeDifferenceForDate 人性化时间、LinkList 传入索引)→ 数据层(Vote 类型与 UsersVotes/VotesOnLink 关系、graphcool push 同步 schema)→ 查询层(ALL_LINKS_QUERY 携带 postedBy 与 votes)→ 变更层(CREATE_VOTE_MUTATION + voteForLink 去重保护)→ 缓存层(update 回调 + readQuery/find/writeQuery 命令式更新)。

核心收获是 Apollo 的命令式 Store API 工作流:readQuery 读取 → 修改数据对象 → writeQuery 写回,三步即可在任意 Mutation 后精确控制缓存状态,并借由缓存的响应式机制自动刷新 Vue 组件。这套模式与 CreateLink 中的缓存更新一脉相承,也是后续实现实时投票(订阅)与排序分页(/top 路由)的基础。感兴趣的读者可继续阅读 8-subscriptions.md(实时更新新链接与新投票)与 9-pagination.md(基于 first/skip/orderBy 的分页,其中 updateStoreAfterVote 携带变量版本的最终形态可见该章)。

登录后查看全文
howtographql