Nuxt.jsに@nuxt/imageを使って画像を設定する方法になります。
@nuxt/imageをインストールする
まずは@nuxt/imageをインストールしていきます。
npm install -D @nuxt/image
# OR
yarn add --dev @nuxt/image
nuxt.config.jsで設定をする
続いてnuxt.config.js
に設定を追加します。
nuxt.config.js
export default {
modules: [
'@nuxt/image',
]
}
target: 'static'
の時はbuildModules
に設定します。
nuxt.config.js
export default {
target: 'static',
buildModules: [
'@nuxt/image',
]
}
@nuxt/imageを使って画像を表示する
<template>
<nuxt-img src="/photo.jpg" />
</template>
nuxt-img
またはnuxt-picture
を使って画像を表示することができます。
<template>
<nuxt-img
src="/photo.jpg"
width="400"
height="200"
loading="lazy"
format="webp"
quality="80"
alt="image"
/>
</template>
オプションの指定も複数可能です。詳しいオプションは下記の公式サイトに記載されています。
background(背景)で@nuxt/imageを使う場合の例
<template>
<div :style="backgroundStyles"></div>
</template>
<script lang="ts">
import Vue from 'vue'
export default Vue.extend({
computed: {
backgroundStyles() {
const imgUrl = this.$img(
'/photo.jpg',
{ width: 400, height: 200, quality: 80 }
)
return {
background: `url('${imgUrl}') repeat left top`
}
}
}
})
</script>
ローカルの画像はstaticフォルダに配置する必要がある
公式サイトにも記載がありますが、nuxt-img
にローカルから画像を設定する場合は、staticフォルダに配置する必要があります。assetsフォルダでは機能しません。
https://image.nuxtjs.org/getting-started/providers
外部にある画像を表示する場合は設定が必要
外部にある画像を@nuxt/imageを使って表示するには、nuxt.config.js
に設定を追加します。
nuxt.config.js
export default {
modules: [
'@nuxt/image',
]
/*
** ↓↓↓追加
*/
image: {
domains: ['nuxtjs.org']
}
}
Contentfulの画像を設定する例
ヘッドレスCMSのContentfulの画像を設定する場合の一例です。
nuxt.config.js
export default {
image: {
provider: 'contentful',
contentful: {
baseURL: 'https://images.ctfassets.net'
}
}
}
参考