LoginSignup
1
2

More than 5 years have passed since last update.

v-bind:srcでハマった

Last updated at Posted at 2018-06-13

nuxtで開発していてハマったので記録を残しておきます。
やりたかったことはオブジェクトの中身を全てrequireして画像を表示したいというものです。

結局問題だったのはWebpackのところで、静的パスを指定する必要がありました。
っていう内容です。

const store = () => new Vuex.Store({

  state: {
    data: {}
  },
  mutations: {
    getDocuments(state) {
      // 画像を取得する
    }
  },
  getters: {
    getImgPath: state => {
      return require(state.data.img) // ここでエラー
    }
  },
  actions: {}
})

静的に指定しなければならないので以下のように修正したところエラーを解消することができました。

const store = () => new Vuex.Store({

  state: {
    data: {}
  },
  mutations: {
    getDocuments(state) {
      // 画像を取得する
    }
  },
  getters: {
    getImgPath: state => {
      // data.imgは画像ファイル名となるようにする
      return require('~/assets/' + state.data.img + '.jpg')
    }
  },
  actions: {}
})

もっとスマートな方法あれば教えて頂きたいです。

1
2
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
2