LoginSignup
11
7

More than 3 years have passed since last update.

Vue.jsかNuxtJSでassetsに入れた画像を動的に表示させる

Last updated at Posted at 2020-01-23

環境

  • NuxtJS v2.11.0
  • TypeScript v3.7.5

問題

リストで管理している画像ファイルを動的に書いてもうまく表示されない

コンポーネント部分

以下のように画像のファイル名リストを文字列で持っていたとする。

import { Vue, Component, Prop } from 'vue-property-decorator'
@Component({})
export default class ImageUnit extends Vue {
  @Prop()
  imageNames: Array<string>
}

テンプレート部分

<template>
  <dl>
    <dt>Image: </dt>
    <dd v-for="(imageName, index) in imageNames" :key="`image-${index}`">
      <img :src="`@/assets/${imageName}`" alt="`image-index`">
    </dd>
  </dl>
</template>

このように書いても、HTMLに直接上記のURLが表示され、画像は出なかった。
staticディレクトリに入れるという手もあるが、Nuxtで管理できないのは困るので別の方法を考えた。

解決策

以下のURLを参考にし、一度モジュールをバインドすればOK。
正常に/_nuxt/assets/hogehoge.png画像が表示された。

<template>
  <dl>
    <dt>Image: </dt>
    <dd v-for="(imageName, index) in imageNames" :key="`image-${index}`">
      <img :src="require(`@/assets/${imageName}`)" alt="`in-${index}`">
    </dd>
  </dl>
</template>
11
7
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
11
7