for通过数组循环并将类绑定到vue.js中的元素类属性 [英] for loop through array and bind class to element class attribute in vuejs

查看:78
本文介绍了for通过数组循环并将类绑定到vue.js中的元素类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过vuejs将类名绑定到class属性中,并通过这样的数组进行循环:

I am trying to bind classnames into the class attribute with vuejs looping through an array like this:

在这里,我在:class = paymentTypeClass (值)来绑定到vue模板,如下所示:

Here I pass the method call in a :class="paymentTypeClass(value)" to bind to the vue template like so:

<li v-for="card in paymentType" class="o-pf-list__item" :class="paymentTypeClass(value)">
  {{ card }}
</li>

new Vue ({
  el: '#app',
  data: {
  paymentType: ['paymentType1', 'paymentType2', 'paymentType3', 'paymentType4', 'paymentType5']
  },
  methods: {
    functionName: function(value) {
      var i = 0;

      for (i in this.paymentType) {

        value = 'o-pf-list__item--' + this.paymentType[i];

      }
      return value + ' pull-left';
    }
  }
});

结果是它只打印出数组中的最后一个索引值,因此实际上是覆盖了。为什么是这样?请帮忙。

The result is that it only prints out the last index value in the array so it is actually overwriting. Why is this? Please help.

登录控制台:

o-pf-list__item--bitcoin
app.js:51663 o-pf-list__item--credit
app.js:51663 o-pf-list__item--debitcard
app.js:51663 o-pf-list__item--eft
app.js:51663 o-pf-list__item--masterpass
app.js:51663 o-pf-list__item--bitcoin
app.js:51663 o-pf-list__item--credit
app.js:51663 o-pf-list__item--debitcard
app.js:51663 o-pf-list__item--eft
app.js:51663 o-pf-list__item--masterpass
app.js:51663 o-pf-list__item--bitcoin
app.js:51663 o-pf-list__item--credit
app.js:51663 o-pf-list__item--debitcard
app.js:51663 o-pf-list__item--eft
app.js:51663 o-pf-list__item--masterpass
app.js:51663 o-pf-list__item--bitcoin
app.js:51663 o-pf-list__item--credit
app.js:51663 o-pf-list__item--debitcard
app.js:51663 o-pf-list__item--eft
app.js:51663 o-pf-list__item--masterpass
app.js:51663 o-pf-list__item--bitcoin
app.js:51663 o-pf-list__item--credit
app.js:51663 o-pf-list__item--debitcard
app.js:51663 o-pf-list__item--eft
app.js:51663 o-pf-list__item--masterpass


推荐答案

您的代码有些混乱。

paymentTypeClass 是什么样?看起来您是否想要基于逻辑的元素上的所有类?如果是这样,您可以这样做:

What does paymentTypeClass look like? It looks like you want all the classes on the element based on your logic? If so you can do like:

paymentTypeClasses () {
  const classes = this.paymentType.map(type => 'o-pf-list__item--' + type)
  classes.push('pull-left')
  return classes
}

然后做

:class="paymentTypeClasses()"

:class="[paymentTypeClasses()]

(易于添加更多类稍后)

(easier to add more classes later)

这篇关于for通过数组循环并将类绑定到vue.js中的元素类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆