DEV Community

Yasunori Tanaka
Yasunori Tanaka

Posted on

Pass parent's async data to child component in NuxtJS

One solution that passes data to a child component as props and gets another async data with the props.

parent component

<template>
  <Selector :user-id="userId"/>
</template>

<script>
import Vue from "vue";
import Selector from "~/components/Selector.vue";

export default Vue.extend({
  components: { Selector },

  data() {
    return {
      userId: undefined
    };
  },

  async fetch() {
    this.userId = await this.$asios.$get("http://example.com");
  }
});
</script>

The parent component passes userId as props.

child component

<template>
  <p v-if="user">{{ user.name }}</p>
</template>

<script>
import Vue from "vue";

export default Vue.extend({
  props: {
    userId: {
      type: String,
      required: true
    }
  },

  data() {
    return {
      user: undefined
    };
  },

  watch: {
    userId() {
      this.getUser();
    }
  },

  methods: {
    async getUser() {
      if (!this.userId) {
        return;
      }

      this.user = await this.$asios.$get("http://example.com/get_user");
    }
  }
});
</script>

After the child component get a userId with watch(), it requests an async user data.

Top comments (0)