sourcecode

Nuxtjs 구성 요소의 비동기 데이터가 작동하지 않습니다.

copyscript 2022. 8. 19. 21:01
반응형

Nuxtjs 구성 요소의 비동기 데이터가 작동하지 않습니다.

nuxt.js 프로젝트에 문제가 있습니다.비동기 컴포넌트를 사용했는데, 컴포넌트가 렌닝되었을 때 비동기 상태가 되지 않았습니다.이건 내 암호야

https://nuxtjs.org/api/에서 문서를 볼 수 있지만 무엇이 문제인지 정확히 알 수 없습니다.

Test.vue(컴포넌트)

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

    <script>

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

    </script>

이것은 index.vue (페이지)

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

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

    </script>

제가 예상한 결과는

bbb

그러나 http://localhost:3000에서 실행할 경우 이는 실제 결과입니다.

아아아.

구글 검색을 여러 번 해보려고 하지만, 나에게 기대되는 해결책은 없습니다.누가 좀 도와주세요.

도와 줘서 고마워.

components/폴더에는 "순수한" Vue.js 컴포넌트만 포함되어 있어야 합니다.

사용할 수 없습니다.asyncData안에서.

다음 FAQ를 참조하십시오.https://nuxtjs.org/faq/async-data-components#async-data-in-components-


컴포넌트/Test.vue(컴포넌트)

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

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

pages/index.vue(페이지)

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

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

구성 요소에서 비동기 데이터를 사용할 수 없습니다.

대신 가져오기 방법을 사용할 수 있습니다.

<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>

언급URL : https://stackoverflow.com/questions/48535181/asyncdata-in-component-of-nuxtjs-isnt-working

반응형