首页 > 解决方案 > Vue.js pass local loop variable to v-bind:style

问题描述

I loop through a list and would like to set a background image according to a property in this list. But in v-bind:stlye the property isn't defined.

How can I pass it?

        <div class="content" v-bind:key="slide.id" v-for="slide in show.slides">
            <div class="slide">
                <div class="model"
                     :style="{ backgroundImage:
                        `url(${strapiUrl + slide.model_media.Media.url})` }">
                    <div class="title">{{slide.title}}</div>
            </div>
        </div>

标签: vue.jsvue-component

解决方案


Perhaps it is simply easier to abstract the entire style binding into a method. In your template, you can simply do this:

<div class="model" v-bind:style="modelStyle(slide)">

Then, in your component, create a modelStyle() method:

modelStyle: function(slide) {
  return {
    backgroundImage: url(`${this.strapiUrl}${slide.model_media.Media.url}`);
  };
}

推荐阅读