简体   繁体   中英

Vue pass data from parent to child component using props?

How do i get topicCategories in the child component. I tried using states below but it is always the previous page topicCategories not the current page.

Parent (post.vue)

export default class MyPost extends mixins(LocaleMixin) {
  Categories: any[] = [];
  topicCategories: any[] = [];

  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);
        this.$store.dispatch('app/setCurrentCategories', topicCategories);

      },
      () => {
        this.$nuxt.error({ statusCode: 404, message: 'err message' });
      }
    );
    this.loading = false;
  }

}

Child Component (readnext.vue)

export default class ReadNext extends mixins(LocaleMixin) {
  offset = 0;
  total = 0;
  topics = [];

async fetch() {
    await this.$apiRequest(async () => {
 
    if(this.$store.state.app.currentCategories.length) {

        const categories = this.$store.state.app.currentCategories.map((category: any) => category.id);
      
        const { data } = await this.$services.topic.fetchReadNext(
            categories,
            this.currentLocale.name,
            10,
            this.offset * 10
        );

        //@ts-ignore
        this.topics.push(...data.rows);

        this.total = data.count;

        this.offset += 10;
        }
    });
  }
}

How do i get this.topicCategories from the parent to the child component without using states?

You need to declare topicCategories as a prop and then pass its value into a template. Here is how to do it: Child:

import { Prop } from 'vue-property-decorator';
export default class ReadNext extends mixins(LocaleMixin) {
   @Prop({default: [], required: true}) topicCategories!: any[];
   ...
}

Parent:

<child :topicCategories="topicCategories" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM