Vue dynamically adds background image

In VUE, set a dynamic style background image for each item in the for loop

There is often a need in VUE projects to render an array in a loop and give each item a different background image. First consider the use of dynamic style, and change the address of the background image according to the index change in the loop.

A simple example:
insert image description here

Easy way to write, directly embed html style

<li v-for="(item,index) in list" :key="index">
  <div class="img-content">
    <div class="bagimg bagimg_one" v-if="index == '0'"></div>
    <div class="bagimg bagimg_two" v-if="index == '1'"></div>
    <div class="bagimg bagimg_three" v-if="index == '2'"></div>
    <div class="bag_img" v-if="index>2" :style="{'background-image':`url(${require(`./assets/ranking${index+1}.png`)}`}"></div>
  </div>
</li>

Another way, you can also handle other logic in the method

The code in html is as follows:

	<div class="bag_img" v-for="(item,index) in list" :key="index" :style="{'background-image':`url(${getImageUrl(index)})`}" >{
   
   {item}}</div>

The code in JS is as follows:

<script>
export default {
    
    
  //****省略
  methods:{
    
    
    getImageUrl(index) {
    
    
	  // 根据索引生成图像URL
      return require(`@/assets/ranking${
      
      index+1}.png`);
    },
  }
};
</script>

It should be noted that the require method needs to be called on the outer layer of the returned address, otherwise webpack will not be able to get the image address after packaging. If it is an http network address, there is no need to call this method.

Guess you like

Origin blog.csdn.net/maocilang/article/details/128904864