You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue路由跳转至博文详情页后如何从Vuex获取对应标题与正文?

解决方案

直接修改博文详情页(Post.vue)代码即可,以下是完整可运行的修改后代码:

<template>
  <div class="post">
      <!-- 标题和正文全部从匹配到的store数据中取 -->
      <h1>{{ currentPost.title }}</h1>
      <p>{{ currentPost.text }}</p>
  </div>
</template>

<script>
export default {
  computed: {
    currentPost() {
      // 将路由参数的id转为数字,匹配store中存储的index字段
      const targetId = Number(this.$route.params.id)
      // 从store的cards数组中找到对应id的博文数据
      return this.$store.state.cards.find(item => item.index === targetId) || {}
    }
  }
}
</script>

<style>

</style>

可选优化(推荐)

如果需要复用单篇博文的查询逻辑,可以在Vuex中新增Getter来封装查找逻辑:

  1. 修改Vuex store配置,新增getters字段:
export default createStore({
    state: {
      // 原有state代码不变
    },
    // 新增以下getters配置
    getters: {
      getPostById: (state) => (id) => {
        return state.cards.find(post => post.index === id) || {}
      }
    },
    mutations: {},
    actions: {},
    modules: {},
});
  1. 详情页的计算属性可以简化为:
currentPost() {
  return this.$store.getters.getPostById(Number(this.$route.params.id))
}

内容的提问来源于stack exchange,提问作者user17466267

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 08:36:00