Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle "active" class between child items vueJS.2

Tags:

vue.js

vuejs2

I just want to know how to do it vue.js way, right now I am able to toggle active class on single item, when I click the other item, the active class still appear on previous item, here is my setup:

FileOne.vue (Parent component)

// Say that I have 5 Items I am rendering here:
<template>
  <ul v-for="item in items">
    <my-list-item :item-title="article.title"
                  :item-content="article.content"> </my-list-item>
  </ul>
</template>

<script>
  import Items from './FileTwo'
  export default {}
</script>

fileTwo.vue (Child components)

// When I click each Item the `active` class should be applied to the current Item and removed from previous item:
<template>
  <li :class="{'active': isRowActive}" @click.stop="toggleRowActive">
    <h1>{{articleTitle}}</h1>
    <p>{{itemContent}}</p>
  </li>
</template>

<script>  
  export default {
    name: 'my-list-item',
    data: function () {
      return {
        isRowActive: false,
      }
    },
    props: {
      articleTitle: String,
      articleContent: String,
    },
    toggleRowFn() {
      this.isRowActive = !this.isRowActive;
      this.showBtnReadContent = true;
    },
  }
</script>
like image 692
Syed Avatar asked Apr 20 '17 06:04

Syed


1 Answers

I usually save the id of the active item in store (Vuex) or data (in component). When the active id is equal to the item id, I set the related class as shown below example.

In the data property:

data: function () {
  return {
   activeItemId: ''
  }
}

in methods:

setActiveItemId(itemIndex) {
    this.activeItemId = itemIndex
}

Template part:

<ul class="ready-design">
<li class="ready-design__item" v-for="(item, itemIndex) in clipArts">
    <a href="javascript:void(0);"
        class="ready-design__link"
        :class="{'is-chosen': activeItemId === itemIndex}"
        @click="setActiveItemId(itemIndex)">
        <img class="..." width="70" height="70" alt="..." src="...">
    </a>
</li>
</ul>

So I don't need remove the class from inactive items.

like image 71
Orkun Tuzel Avatar answered Sep 21 '22 15:09

Orkun Tuzel