Vue父子组件传值:无需状态管理,如何传递topicCategories?
解决Vue父组件向子组件传递数据时旧数据问题(改用Props替代Vuex)
之前通过Vuex传递topicCategories给子组件时,总是获取到上一页的旧数据,下面是改用Props实现正确传递的具体修改方案:
1. 修改父组件(post.vue)
在父组件模板中引入子组件,通过Props传递topicCategories,同时用v-if确保数据加载完成后再渲染子组件,避免子组件拿到空值:
<template> <!-- 其他父组件内容 --> <ReadNext v-if="!loading" :topic-categories="topicCategories" /> </template> <script lang="ts"> export default class MyPost extends mixins(LocaleMixin) { Categories: any[] = []; topicCategories: any[] = []; loading = false; async mounted() { this.loading = true; await this.$apiRequest( async () => { const { data: { id, topicCategories, }, } = await this.$services.topic.fetchTopic( this.$route.params.slug, this.currentLocale.name ); this.Categories = topicCategories as ICategory[]; this.topicCategories = this.Categories.map((category: any) => category.id); // 移除Vuex相关逻辑,直接通过Props传递数据 }, () => { this.$nuxt.error({ statusCode: 404, message: 'err message' }); } ); this.loading = false; } } </script>
2. 修改子组件(readnext.vue)
定义Props接收父组件传递的topicCategories,监听Props变化并重新触发数据获取,替换原Vuex取数逻辑:
<script lang="ts"> export default class ReadNext extends mixins(LocaleMixin) { offset = 0; total = 0; topics = []; // 定义接收的Props props: { topicCategories: { type: Array, required: true, default: () => [] } } async fetch() { if (this.topicCategories.length) { await this.$apiRequest(async () => { const { data } = await this.$services.topic.fetchReadNext( this.topicCategories, this.currentLocale.name, 10, this.offset * 10 ); //@ts-ignore this.topics.push(...data.rows); this.total = data.count; this.offset += 10; }); } } // 监听数据变化,重置状态并重新请求 watch: { topicCategories: { immediate: true, // 组件初始化时触发一次 handler() { this.offset = 0; this.total = 0; this.topics = []; this.fetch(); } } } } </script>
关键说明
- 父组件通过
v-if="!loading"保证子组件在数据就绪后渲染,避免初始化时拿到空数据 - 子组件通过
watch监听Props变化,当父组件数据更新时自动重置分页状态并请求最新数据,彻底解决旧数据问题 - 移除Vuex依赖后,数据流向更直接清晰,避免了状态管理中的异步更新延迟
内容的提问来源于stack exchange,提问作者user892134
相关产品推荐
相关产品推荐

