Toggle the "active" class between vueJS.2 children

I just want to know how to do this vue.js, right now I can switch the class activeto one element, when I click on another element, the class activeis still displayed in the previous element, here is my setting:

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>
+6
source share
2 answers

One possible solution: https://jsfiddle.net/wostex/63t082p2/28/

: , "change property" . Li Boolean active, .

<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
<ul>
  <my-list-item :title="item.title"
      :content="item.content"
      v-for="(item, index) in items"
      :active="index === activeLiIndex"
      :index="index" 
      :key="item.title"
      @newactive="activeLiIndex = $event"      
      ></my-list-item>
</ul>
</div>

<script type="text/x-template" id="my-list-item">
  <li :class="{'active': active}" @click.stop="toggleRowActive">
    <h1>{{title}}</h1>
    <p>{{content}}</p>
  </li>
</script>

new Vue({
    el: '#app',
    data: {
      items: [
        {title: 'Title 1', content: 'Content 1'},
        {title: 'Title 2', content: 'Content 2'}
      ],
      activeLiIndex: null
  },
  components: {
    'my-list-item': {
        template: '#my-list-item',
        props: ['title', 'content', 'active', 'index'],
        methods: {
          toggleRowActive() {
            this.$emit('newactive', this.index);
          }
        }
      }
    }
});  

, , v-for . ul li .

+8

(Vuex) ( ). id id , , .

data:

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

:

setActiveItemId(itemIndex) {
    this.activeItemId = itemIndex
}

:

<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>

.

+9

Source: https://habr.com/ru/post/1016650/


All Articles