Search code examples
ruby-on-railswebpackwebpackerruby-on-rails-6

How to set backgrond image inside vue component in rails 6?


I am trying to set background image inside one of the vue component. I am using rails 6. The images are located inside app/assets/images folder. The vue components are located inside app/javascripts/pages/Login.vue

The following code works:

<v-img :src="require('../../assets/images/logo.png')"/>

However, this does not work:

<v-flex xs3 :style="'background-image: url(' + require('../../assets/images/site-banner.png') + ')'">
...
</v-flex>

Any help is appreciated. Thanks.


Solution

  • I suggest you should remove require in the :style and make sure the path of image can be access from url. Require is keyword for javascript importing, not for :style, or you can assign the path of image as a data attribute to add to :style

    I did that locally and it works

    const imagePath = 'YOUR_HOST_NAME/assets/logo.png';
    
    export default {
    
      computed: {
    
         myStyle() {
          return {"background-image": 'url(' + imagePath + ')'}
         }
    
    }
    

    Then you can use myStyle as :style="myStyle"