1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Nuxt.jsに@nuxt/imageを使って画像を設定する方法

Last updated at Posted at 2022-06-15

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

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?