DEV Community

Yasunori Tanaka
Yasunori Tanaka

Posted on

5 3

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay