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来封装查找逻辑:
- 修改Vuex store配置,新增getters字段:
export default createStore({ state: { // 原有state代码不变 }, // 新增以下getters配置 getters: { getPostById: (state) => (id) => { return state.cards.find(post => post.index === id) || {} } }, mutations: {}, actions: {}, modules: {}, });
- 详情页的计算属性可以简化为:
currentPost() { return this.$store.getters.getPostById(Number(this.$route.params.id)) }
内容的提问来源于stack exchange,提问作者user17466267
相关产品推荐
相关产品推荐

