Nuxt에서 데이터를 가져오는 방법이 두 가지 있습니다.
- asyncData
- fetch
Nuxt에서 클라이언트 사이드 방식이 mounted()를 통해서 데이터를 호출할 수는 방식을 지원하긴 합니다.
하지만 서버 측에서 데이터를 렌더링 하는 앱을 만들기 위해서는 위 두 가지 훅을 사용해야 합니다.
asyncData
- 페이지 내에서만 사용 가능
- 비동기적으로 생성되는 데이터일 때 사용
- 생성한 데이터는 data()로 생성한 데이터와 병합
- data()와 차이 없음 단지 동기 / 비동기 차이
- this 사용 불가능
async asyncData({ params }) {
const response = await fetch(`https://api.example.com/data/${params.id}`);
const data = await response.json();
return { myData: data };
},
fetch
- 캐싱 사용가능
- 쿼리 스트링 변경 사항 감시 가능
- 오류 처리 가능
async fetch({ store, param }) {
const response = await fetch('https://api.example.com/other-data');
const data = await response.json();
this.otherData = data;
},
asyncData vs fetch
asyncData 와 fetch는 비슷한점이 많습니다만,
차이점은 아래와 같습니다.
asyncData | fetch | |
사용 범위 | 페이지 컴포넌트에서만 가능 | 모든 컴포넌트에서 가능 |
this | 접근 불가 | 접근 가능 |
데이터 | data와 병합 | 로컬 데이터 변경 가능 |
결론
Nuxt 2.12 버전 업데이트로 fetch에서 새로운 기능들이 추가되었습니다.
- 로컬 데이터 변경
- layout과 자식 컴포넌트에서 fetch 호출 가능
- 오류 처리 가능
- 서버에서 fetch 비활성화 가능
- fetch 메서드 호출 가능
- 캐싱으로 인한 성능 향상
다양한 기능이 추가 제공 되어서 조금 더 유연하게 사용할 수 있습니다.
그래서 무엇을 써야 하는가?
개발자의 설계에 따라서 asyncData 또는 fetch를 사용하시면 됩니다.
https://v2.nuxt.com/docs/features/data-fetching/#async-data
Data Fetching
In Nuxt we have 2 ways of getting data from an API. We can use the fetch method or the asyncData method.
v2.nuxt.com
https://v2.nuxt.com/docs/concepts/nuxt-lifecycle/
Nuxt Lifecycle
No matter which tool you use, you will always feel more confident when you understand how the tool works under the hood. The same applies to Nuxt.
v2.nuxt.com
https://nuxt.com/blog/understanding-how-fetch-works-in-nuxt-2-12
Understanding how fetch works in Nuxt 2.12 · Nuxt
Go back to articles April 6, 2020 - Release Understanding how fetch works in Nuxt 2.12 Explore different features of the fetch hook and learn a brand new way to bring data into Nuxt applications.
nuxt.com
https://stackoverflow.com/questions/49251437/difference-between-asyncdata-vs-fetch
Difference between Asyncdata vs Fetch
What is the exact difference between fetch and async data. The official documentation says the following: asyncData You may want to fetch data and render it on the server-side. Nuxt.js adds an asy...
stackoverflow.com