Search code examples
vue.jsdata-bindingbackground-imagerendercomputed-properties

Vue.js rendering v-bind:style background-image url with custom computed property does not work


// Component.vue with computed property - Does not work

<template>
<section class="background" v-bind:style="{
    'background-image': 'url(' + require(imageUrl) + ')'}"> . 
</section>
</template>

<script>
export default {
   computed: {
     imageUrl() {
         return './path/to/image';
     }
   }
}
</script>

// Component.vue - Direct approach works

<template>
<section class="background" v-bind:style="{
    'background-image': 'url(' + require('./path/to/image.jpg') + ')'}"> . 
</section>
</template>

The reason for the former implementation is that I need a computed property which could be generated random every time there is a reload.

Here is the full error message for computed property case

[Vue warn]: Error in render: "Error: Cannot find module '../assets/media/images/1.jpg'"

found in

---> <Background>
       <App> at src/App.vue
         <Root>
warn @ vue.runtime.esm.js?2b0e:587
logError @ vue.runtime.esm.js?2b0e:1733
globalHandleError @ vue.runtime.esm.js?2b0e:1728
<stack trace> // I can not post the full message since it is not allowable by the policy of stackoverflow

Solution

  • Please change code as below.

       computed: {
         imageUrl() {
             return require('./path/to/image');
         }
       }
    

    sorry I'm not familiar with this behavior, but as far as I searched, your problem might relates what the following page of Vue Loader says.

    Asset URL Handling | Vue Loader