How to change style of element based on different data

时间:2017-10-12 10:13:14

标签: vue.js vuejs2

I have a user's profile page, and depending on the user type I have status of variable that changes. There are the statuses

0 gues user
1 user registered but email not verified
2 user registered and verified
3 user blocked

I am trying to show an icon instead of the numbers, so I am doing it this way

...

<span v-if='user.status == 0' class='fa fa-close'> </span>
<span v-if='user.status == 1' class='fa fa-envelope'> </span>
<span v-if='user.status == 3' class='fa fa-check'> </span>
<span v-if='user.status == 4' class='fa fa-ban'> </span>

...

As you can see this code is very verbose and I am looking for something to avoid writing a code like this.

1 个答案:

答案 0 :(得分:1)

You should take a look at the Class Binding documentation

In your example, you could bind the icon, based on the user's status. The template will look like :

<span :class=`fa fa-${getIconFromStatus(user.status)}`></span>

And in the component's script, you'll add this method :

getIconFromStatus(status) {
  switch (status) {
    case 0 : 
      return 'close';
    [...]
  }
}
相关问题