O diretório components
O diretório components
contém seus componentes Vue.js. Os componentes são os que compõe as diferentes partes da sua página e podem ser reutilizados e importados dentro das suas páginas, dos esquemas e até dentro de outros componentes.
Requisição de dados
Para acessar dados assíncronos a partir de uma API dentro dos seus componentes você pode usar o método fetch()
do Nuxt.
Ao verificar o $fetchState.pending
, nós podemos exibir uma mensagem quando os dados estiverem esperando para serem carregados. Nós podemos também consultar o $fetchState.error
e exibir uma mensagem de erro se houver um erro na requisição dos dados. Sempre que estivermos usando o método fetch()
, nós devemos declarar as propriedades apropriadas dentro do método data()
. Os dados que vierem da requisição podem então ser atribuídos à estas propriedades.
<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>
Descoberta de componentes

A partir da versão v2.13
, o Nuxt pode importar automaticamente os componentes que você usar. Para ativar esta funcionalidade, defina components: true
dentro da sua configuração:
export default {
components: true
}
Qualquer componente dentro do diretório ~/components
podem então ser usados em todas as suas páginas, esquemas (e outros componentes) sem a necessidade de explicitamente importar eles.
| components/
--| TheHeader.vue
--| TheFooter.vue
<template>
<div>
<TheHeader />
<Nuxt />
<TheFooter />
</div>
</template>
Importação dinâmica
Para importar dinamicamente um componente, também conhecido como carregamento preguiçoso de um componente, tudo o que você precisa fazer é adicionar o prefixo Lazy
dentro dos seus modelos.
<template>
<div>
<TheHeader />
<Nuxt />
<LazyTheFooter />
</div>
</template>
Ao usar o prefixo lazy você pode também dinamicamente importar um componente quando um evento for acionado.
<template>
<div>
<h1>Mountains</h1>
<LazyMountainsList v-if="show" />
<button v-if="!show" @click="show = true">Show List</button>
</div>
</template>
<script>
export default {
data() {
return {
show: false
}
}
}
</script>
Diretórios aninhados
Se você tiver componentes dentro de diretórios aninhados tais como:
components/
base/
foo/
CustomButton.vue
O nome do componente será baseado no seu próprio caminho do diretório e nome de ficheiro. Portanto, o componente será:
<BaseFooCustomButton />
Se nós quisermos usar ele como <CustomButton />
enquanto mantém a estrutura do diretório, nós podemos adicionar o diretório de CustomButton.vue
dentro de nuxt.config.js
.
components: {
dirs: [
'~/components',
'~/components/base/foo'
]
}
E agora podemos usar o <CustomButton />
ao invés de <BaseFooCustomButton />
.
<CustomButton />


















































