LoginSignup
14
7

More than 3 years have passed since last update.

ハマりメモ:bootstap-vueでb-imgのsrc属性に相対パスが指定出来ない。

Last updated at Posted at 2019-05-31

bootstap-vueでb-imgのsrc属性に相対パスが指定出来ない。

結論から言えば、Bootstrap-vueでは、2019/5/31現在、デフォルトではsrc属性に相対パスを指定しても、画像が表示されません。

vue-loaderの設定を少し書き加える必要があります。

ハマり発生

「ここにテキストをここに画像を貼って2カラムのレイアウト作るぞ。」

hoge.vue
<template>
  b-container.hoge-container
    b-row(align-v="center").hoge-contents
      b-col(md="6")
        p hogehoge
      b-col(md="6")
        b-img(fluid src="../static/images/hoge.jpg" alt="hoge")
</template>

上手くいきません。

ググります。

公式にありました。

https://bootstrap-vue.js.org/docs/reference/images/

解決方法

大体の内容は、vue-loaderは<img>タグのsrc属性のに相対パスを書いても自動的に変換するけど、BootstrapVueカスタムコンポーネントの場合は自動的には変換しませんよ。

不親切です。
b-img何て特別な書き方してて、ただでも初級者には、bootstrapやっとうろ覚えてきたに、また方言〜というところなのに、デフォルトでは使えないから、よろしくね、なんて。。。

気をとり直して読んでいくと、Vue-Loaderのoption設定でb-imgとかb-cardとかに相対URLが結びつくように設定してよとVue-CLI3とNuxtでの設定方法が書いてありした。

module.exports = {
  build: {
    extend(config, ctx) {
      const vueLoader = config.module.rules.find(rule => rule.loader === 'vue-loader')
      vueLoader.options.transformAssetUrls = {
        video: ['src', 'poster'],
        source: 'src',
        img: 'src',
        image: 'xlink:href',
        'b-img': 'src',
        'b-img-lazy': ['src', 'blank-src'],
        'b-card': 'img-src',
        'b-card-img': 'img-src',
        'b-card-img-lazy': ['src', 'blank-src'],
        'b-carousel-slide': 'img-src',
        'b-embed': 'src'
      }
    }
  }
}

これで画像が表示されました。

またrequire使っても出来るようです。

b-img(:src="require('../static/hoge.jpg')")

b-card-img(:img-src="require('../static/picture.jpg')"

まとめ

デフォルトで当たり前のよう出来そうな事が案外出来ないですよね。

webpackの周りの復習が出来たし、Nuxt、vue-loaderの公式の今まで読んでなかったページをまじまじと読めたので良かったという事にします。

該当箇所のソースです。


Nuxt => https://ja.nuxtjs.org/api/configuration-build/
bootstrap-vue => https://bootstrap-vue.js.org/docs/reference/images/
vue-loader => https://vue-loader.vuejs.org/options.html#transformasseturls

14
7
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
14
7