How do I bind a style to my v-for loop in this exa

2019-08-19 00:41发布

What am I doing wrong here? There is no error - but there is also no style being applied when I look via dev tools.

<!-- Template -->
<td v-for="steps in item.steps" v-bind:style="steps.name">
 {{ steps.name }}
</td>

// Component definition
computed: {
  endstage() {
    return {
      'background-color': '#f9f9f9',
    };
  }
}

steps.name prints and if I bind class to steps.name that works - so not sure what I'm doing wrong with trying to bind style.

update:

In my template, I also am using this example which works fine:

<!-- Template -->
<table :style="tableStyle">

// Component definition
computed: {
  tableStyle() {
    return {
      'background-color': '#f9f9f9',
      'border-color': '#C0C0C0',
      'padding': '8px',
      'color': 'red',
      'width': '100%',
      'display': 'table',
      'border': '1px solid #ddd',
    };
  }
}

So why can I not do the same for td using steps.name which in this example results in 'endstage'?

标签: vue.js
2条回答
劳资没心,怎么记你
2楼-- · 2019-08-19 01:32

It must be v-bind not v:bind.

查看更多
女痞
3楼-- · 2019-08-19 01:35

The output of your template will be something like this:

<td style="endstage">
  endstage
</td>

I'm assuming that isn't what you want as endstage is not a valid value for the style attribute. Note that the computed property isn't being used at all here. It is just trying to set the style to the string 'endstage'.

I guess what you're trying to do is this?

<td v-for="steps in item.steps" :style="this[steps.name]">

Assuming steps.name is 'endstage', this will use the object returned by the computed property endstage as the style. this[steps.name] evaluates as this['endstage'], which is just this.endstage.

It's not a great strategy though as it assumes that all names will have their own computed properties.

If endstage is the only name you care about then you could do something like this:

<td v-for="steps in item.steps" :style="steps.name === 'endstage' ? endstage : null">

If there are others then it'd be better to use a method:

<td v-for="steps in item.steps" :style="getStyle(steps.name)">

with:

methods: {
  getStyle (name) {
    switch (name) {
      case 'endstage':
        return {'background-color': '#f9f9f9'}
      // Other cases here
    }
  }
}
查看更多
登录 后发表回答