[Vuejs]-VueJs conditional class/style binding?

3đź‘Ť

âś…

It’s probably best to wrap everything inside the loop into its own component and pass the data in as a prop. If you do so, you’ll have your own scope in this component where you can just have a regular computed() without many if/else checks.

For simple cases, you can also do your logic directly in the template:

<v-list v-for="(icon,i) in iconActions"
    :key="`${i} - ${icon}`"
    :class="{ 'white--text': $route.params.page === icon.icon }">
  <v-list-tile>
    <v-icon>{{icon.icon}}</v-icon>
  </v-list-tile>
</v-list>
👤ssc-hrep3

0đź‘Ť

Here’s the code (not runnable because I don’t have the full context btw).

The idea: get highlightIconIndex in computed, compare it with i in v-for by “the Vue conditional rendering” v-if v-else.

I don’t quite sure what you mean about highlight, just give the code a look and see if it’s what you want.

new Vue({
  el: '#app',
  data() {
    return {
      iconActions: [
        { icon: 'android' },
        { icon: 'dashboard' },
        { icon: 'book' },
        { icon: 'public' },
        { icon: 'timeline' }
      ],
    }
  },
  computed: {
    highlightIconIndex() {
      if (this.$route.params.page === 'something') {
        return 0;
      } else if (this.$route.params.page === 'something else') {
        return 1;
      }
    } 
  }
})
.highlight {
  background: red;
  color: yellow;
}
<div id="app">
  <v-app>
    <v-list v-for="(icon,i) in iconActions" :key="`${i} - ${icon}`">
      <v-list-tile>
        <v-icon v-if="i === highlightIconIndex" class="highlight">{{icon.icon}}</v-icon>
        <v-icon v-else>{{icon.icon}}</v-icon>
      </v-list-tile>
    </v-list>
  </v-app>
</div>

Leave a comment