Nuxt项目中如何根据下拉分类选择值更新独立的博客卡片组件
问题原因
你当前的核心问题出在Vuex mutation的实现逻辑和数据流向错误:
- Vuex的
mutation必须直接修改state中的属性才能触发响应式更新,你写的filtermutation只是返回了筛选结果,没有对state做任何修改,自然不会触发状态更新。 - 不要直接修改原始博客数组,否则切换其他分类时会丢失全量数据,合理的方案是单独存储选中的分类ID,基于ID做动态筛选。
- Card组件直接读取原始的
state.blogs,没有和筛选逻辑关联,自然不会同步筛选结果。
修复步骤
1. 调整Vuex的store逻辑
修改store/index.js,新增选中分类ID存储、修正mutation、优化getter:
import blogsGQL from '~/graphql/blog/blog.graphql' export const state = () => ({ blogs: [], // 新增:存储选中的分类ID,0默认展示全部 selectedCategoryId: 0 }) export const actions = { async nuxtServerInit({ commit }, context) { const client = context.app.apolloProvider.defaultClient const response = await client.query({ query: blogsGQL }) commit('setBlogs', response.data.blogs) } } export const mutations = { setBlogs(state, blogs) { state.blogs.push(...blogs) }, // 替换原有错误的filter mutation,仅修改选中的分类ID setSelectedCategoryId(state, categoryId) { state.selectedCategoryId = categoryId } } export const getters = { // 优化getter,自动根据选中ID返回筛选后的数据 filteredBlogs: state => { if (state.selectedCategoryId === 0) return state.blogs return state.blogs.filter(blog => blog.category_id === state.selectedCategoryId) } }
2. 简化FilterComponent逻辑
你已经在服务端初始化时拉取了全量博客数据,不需要再重复发GraphQL请求,直接监听下拉选中值更新state即可:
export default { name: 'FilterComponent', props: { categories: { type: Array, required: true } }, data() { return { selected: 0 } }, // 新增监听,选中分类时更新Vuex状态 watch: { selected(newVal) { this.$store.commit('setSelectedCategoryId', newVal) } } // 删掉原有重复请求的apollo配置即可 }
如果你的业务场景要求每次选分类都拉取服务端最新数据,不需要前端全量筛选,只需要在Apollo的update回调里把拉到的新博客列表提交到mutation覆盖state.blogs即可。
3. 修改Card组件的数据源
让Card组件读取筛选后的getter数据,而非原始的全量博客:
computed: { blogs() { return this.$store.getters.filteredBlogs } }
内容的提问来源于stack exchange,提问作者niels van hoof
相关产品推荐
相关产品推荐

