andrerpena andrerpena - 2 months ago 23
Javascript Question

How can I bind a class attribute to an expression in Vue 2.0?

I had this in Vue 1.0:

<div v-for="menuItem in menu" class='vnav-item-wrapper'>
<i v-show="menuItem.icon" class="vnav-icon fa fa-{{menuItem.icon}}"></i>
</div>


But now the
{{}}
construct is obsolete in Vue 2.0.

I just read through the Class and Style guide and it simply doesn't seem to be possible for me to bind a class to
"fa-" + menuItem.icon
. I can't bind to an expression.

The closest I got was calculated data properties but then again, I'm in the middle of a
v-for
, I can't create "calculated variables".

How do I solve that?

Tom Tom
Answer

I think this other question shows you how. It was definitely not obvious to me that once you apply v-bind: (or the : short-hand) to an attribute it's all interpreted as though it were JavaScript. So I think what you want is:

<div v-for="menuItem in menu" class='vnav-item-wrapper'>
  <i v-show="menuItem.icon" :class="'vnav-icon fa fa-' + menuItem.icon"></i>
</div>