loading...

Pass parent's async data to child component in NuxtJS

yasunoritanaka profile image Yasunori Tanaka ・1 min read

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.

Posted on by:

yasunoritanaka profile

Yasunori Tanaka

@yasunoritanaka

I'm Yasunori Tanaka (田中 穏識). I'm a full-stack software engineer in Tokyo.

Discussion

pic
Editor guide