ThangLe
ThangLe

Reputation: 970

asyncData in component of Nuxtjs isn't working

I have an issue with the nuxt.js project. I used async the component but when it rending, async wasn't working. This is my code.

I have view document in https://nuxtjs.org/api/ but I don't know what is exactly my issue

Test.vue (component)

    <template>
        <div>
            {{ project }}
        </div>
    </template>

    <script>

    export default {
        data() {
            return {
                project : 'aaaa'
            }
        },
        asyncData() {
            return {
                project : 'bbbb'
            }
        }
    }

    </script>

This is index.vue (page)

    <template>
        <test></test>
    </template>
    <script>

    import Test from '~/components/Test.vue'
    export default {
        components : {
            Test
        }
    }

    </script>

My expected result is

    bbbb

But when running on http://localhost:3000 this is actual result

    aaaa

I try to search google many times but don't have expected solution for me. Someone help me, please.

Thanks for helping.

Upvotes: 15

Views: 21454

Answers (2)

You cannot use asyncData in component.

You can choose to use the fetch method instead.

<template>
  <div>
    <p v-if="$fetchState.pending">Loading....</p>
    <p v-else-if="$fetchState.error">Error while fetching mountains</p>
    <ul v-else>
      <li v-for="(mountain, index) in mountains" :key="index">
        {{ mountain.title }}
      </li>
    </ul>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        mountains: []
      }
    },
    async fetch() {
      this.mountains = await fetch(
        'https://api.nuxtjs.dev/mountains'
      ).then(res => res.json())
    }
  }
</script>

Upvotes: 8

Nicolas Pennec
Nicolas Pennec

Reputation: 7631

The components/ folder must contains only "pure" Vue.js components

So you can't use asyncData inside.

Read this FAQ: https://nuxtjs.org/faq/async-data-components#async-data-in-components-


components/Test.vue (component)

<template>
    <div>
        {{ project }}
    </div>
</template>

<script>
export default {
    props: ['project'] // to receive data from page/index.vue
}
</script>

pages/index.vue (page)

<template>
    <test :project="project"></test>
</template>

<script>
import Test from '~/components/Test.vue'
export default {
    components : {
        Test
    },
    asyncData() {
        return {
            project : 'bbbb'
        }
    }
}
</script>

Upvotes: 35

Related Questions