簡體   English   中英

Vue使用道具將數據從父組件傳遞到子組件?

[英]Vue pass data from parent to child component using props?

如何在子組件中獲取topicCategories 我嘗試使用下面的狀態,但它始終是上一頁topicCategories而不是當前頁面。

父級(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;
  }

}

子組件(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;
        }
    });
  }
}

如何在不使用狀態的情況下從父組件獲取this.topicCategories到子組件?

您需要將 topicCategories 聲明為 prop,然后將其值傳遞給模板。 操作方法如下: 孩子:

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

家長:

<child :topicCategories="topicCategories" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM