[Vuejs]-Active a item inside a v-for loop when clicked

4👍

Your code has a couple problems:

  • instead of :style="panel.color", you should put in an object, so it should be :style="{ color: panel.color }"
  • you forgot to add a click handler, i.e., you should add v-on:click="..."

Note: To simplify things, I didn’t use your getPanels but use an array instead, it shouldn’t affect how you understand how everything works.

const app = new Vue({
  el: '#app',
  data: {
    panels: [
      {section: 'One', action: 'Action 1', color: 'red' },
      {section: 'Two', action: 'Action 2', color: 'blue' },
      {section: 'Three', action: 'Action 3', color: 'green' },
      {section: 'Four', action: 'Action 4', color: 'orange' },
      {section: 'Five', action: 'Action 5', color: 'purple' }
    ],
    activeItem: -1
  },
  methods: {
    clickHandler(idx) {
      this.activeItem = idx
    }
  }
});
.active {
    opacity: 0.7;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div id="app">
  
  <div class="panel panel-default">
    <ul class="list-group">
      <li 
        class="list-group-item"
        v-for="(panel, index) in panels"
        :class="{active: index === activeItem}" 
        :style="{ color: panel.color }"
        v-on:click="clickHandler(index)"
      >
        A section {{panel.section}} was {{panel.action}}
      </li>
    </ul>
  </div>

</div>
👤kevguy

Leave a comment