简体   繁体   中英

Dynamic background image based on javascript variable

In my style block I have code like this

<style lang="scss">
    .item {
        background: url('~@assets/images/i10.png');
    }
</style>

As per my specific needs I need to load the image from the javascript variable thats being injected in html page. eg in index.html file coming up from server it could be

itemURL = '/abc/def/def/img.png';

Something like:

<style lang="scss">
    .item {
        background: url([window.itemURL);
    }
</style>

and then I need to use that url as background image of item.

I can't use document.getElementBy(xyz) as item is loading/unloading dynamically into DOM.

Note: Its vuejs project created via vue command line tools

u can use img tag instead of css style

<template>
  <div>
      <img
        :src="url"
      >
  </div>
</template>

<script>
export default {
  data() {
    return {
      url: null
    }
  },
  mounted() {
    this.url = injectImageUrl() // js function to inject url
  }
}
</script>

Maybe you can use props? But I don't think it's possible to access the props from inside the style tag. The only way to do this is by using inline styling.

<template>
  <div :style={ backgroundImage: 'url('+ imgUrl +')' }>
         
  </div>
</template>

<script>
  export default {
    props: {
      imgUrl: {
        type: String,
      }
    },
  }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM