Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle class in vue js of a specific item in v-for

How can i toggle by btn specific div from list of items , which one i got from json and display using v-for ?

I am understand that i can`t just set v-if to div and add to vue data , but in this case it fill open and close all divs

 <div class="about" v-if="list">
                  <div class="dat"  v-for="data in item.items_situation" :key="data.a">
                        {{data.doc_valid_through}}
                        {{data.document_type}}
                        {{data.item_nr_full}}
                        {{data.item_text}}
                </div>
                <div class="situation-btn">
                    <input class="situatuin-btn" type="submit" value="Подбробнее" v-on:click="hide">
                </div>
            </div>

When i click the button i want to toggle one div not all

like image 622
Bravis Avatar asked Nov 24 '25 09:11

Bravis


1 Answers

There are many ways to achieve this, I'll provide one for you.

  1. Map your JSON array in data by adding visible property for every item.
  2. Add button inside loop (so its attached for every item) and make visible = false by clicking it.
  3. Display filtered results (visible === true only)

new Vue({
  el: "#app",
  
  data: {
    items: [
      { text: "Learn JavaScript", id: 1 },
      { text: "Learn Vue", id: 2 },
      { text: "Play around in JSFiddle", id: 3 },
      { text: "Build something awesome", id: 4 }
    ].map(item => ({...item, visible: true})),
    
    hiddenItems: []
  },
  
  
  computed: {
    visibleItems() {
      return this.items.filter(item => item.visible)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div class="dat" v-for="item in visibleItems" :key="item.id">
    {{item.text}}
    <button v-on:click.prevent="item.visible = false">X</button>
  </div>
</div>
like image 59
Emīls Gulbis Avatar answered Nov 25 '25 23:11

Emīls Gulbis