问题
I am trying to bind classnames into the class attribute with vuejs looping through an array like this:
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.
Logs in the console:
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
回答1:
Your code is a little confusing.
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
}
Then do
:class="paymentTypeClasses()"
or
:class="[paymentTypeClasses()]
(easier to add more classes later)
来源:https://stackoverflow.com/questions/45163329/for-loop-through-array-and-bind-class-to-element-class-attribute-in-vuejs