LoginSignup
22
12

More than 5 years have passed since last update.

nuxt.jsで:src="require(変数)"で画像パスを指定する時に。。

Last updated at Posted at 2019-02-03

nuxt.jsでサイトを作る際にちょっと詰まったのでメモ。

詰まったところ

nuxt.jsはassetsに画像ファイルを置くとsrc="require('@/assets/hoge.jpg')"で参照出来るので、
繰り返しの要素で変数に画像パスを格納して、それを使って画像を表示させようとしました。
しかしどんなにパスを確認しても、`Cannot find module '@/assets/hoge.jpg'"と、画像が参照出来ませんでした。

hoge.vue
<template lang="pug">
  v-container(grid-list-lg fluid pa-0)
    v-layout(row wrap)
      template(v-for="(pr, index) in prContents")
        v-flex(xs12 md4 :key="index")
          v-card
            v-img(:src="require(pr.image)" height="300")
            v-container(fill-height fluid pa-2)
              v-layout(fill-height)
                v-flex(xs12 align-end flexbox)
                  span(class="headline white--text" v-text="pr.title")
</template>

<script>
export default {
  name: 'HomeConcept',
  data () {
    return {
      prContent: [
        {
          title: 'タイトル1',
          contents: 'コンテンツ',
          image: '@/assets/hoge1.jpg'
        },
       {
          title: 'タイトル2',
          contents: 'コンテンツ',
          image: '@/assets/hoge2.jpg'
        },
       {
          title: 'タイトル3',
          contents: 'コンテンツ',
          image: '@/assets/hoge3.jpg'
        },
      ]
    }
  }
}
</script>

<style scoped  lang="stylus">

</style>

解決策

require内で、パスが単純な文字列として認識されてnuxt.jsの@が解決出来ず、参照出来ないため、
require()をdataオブジェクトの中で実行するように変更します。

data() {
  return {
    prContents: [
      {
        title: "タイトル1",
        contents: "コンテンツ",
        image: require("@/images/hoge.jpg")
      }
    ]
  }
}

修正コード

hoge.vue
<template lang="pug">
  v-container(grid-list-lg fluid pa-0)
    v-layout(row wrap)
      template(v-for="(pr, index) in prContents")
        v-flex(xs12 md4 :key="index")
          v-card
            v-img(:src="pr.image" height="300")
            v-container(fill-height fluid pa-2)
              v-layout(fill-height)
                v-flex(xs12 align-end flexbox)
                  span(class="headline white--text" v-text="pr.title")
</template>

<script>
export default {
  name: 'HomeConcept',
  data () {
    return {
      prContents: [
        {
          title: 'タイトル1',
          contents: 'コンテンツ',
          image: require('@/assets/hoge1.jpg')
        },
        {
          title: 'タイトル2',
          contents: 'コンテンツ',
          image: require('@/assets/images/3pr-medical.jpg')
        },
        {
          title: 'タイトル3',
          contents: 'コンテンツ',
          image: require('@/assets/images/3pr-compassionate.jpg')
        }
      ]
    }
  }
}
</script>

<style scoped  lang="stylus">

</style>

22
12
1

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
22
12