How can I use vue.js environment variables like BASE_URL at CSS background: url(...)

Viewed 766

I am trying to solve the challegene like

<template>
 <div :style="{background: 'url($publicPath)img.gif'}"></div>
</template>

<script>
 export default {
  data() {
   return {
    publicPath: process.env.BASE_URL
   }
  }
 }
</script>

but it doesn't work.

1 Answers

You can easily render the image using template string like:

<div :style="{background: `url(${publicPath}img.gif)`}"></div>

Demo:

new Vue({
  el: "#myApp",
  data() {
   return {
    publicPath: 'https://www.w3schools.com/html/'
   }
  }
})
.image { width:200px; height: 200px}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="myApp">
  <div :style="{background: `url(${publicPath}pic_trulli.jpg)`}" class="image"></div>
</div>

Related