3
votes

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

2
share code snippet ?Niklesh Raut

2 Answers

3
votes

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

You can use v-bind:class to dynamically add class to elements. Code should be like this:

<div class="about" v-if="list">
    <div v-for="data in items" v-bind:class="{hide: data.isHidden}" :key="data.key">
        Something
    </div>
    <div class="situation-btn">
        <input class="situatuin-btn" type="submit" value="Подбробнее" v-on:click="hide">
    </div>
</div>

Then in hide

hide(){
    this.items[i].isHidden = true
}

The data.isHidden property decides whether an element in list should have hide class. See also Class and Style Bindings.

-------Edited-------

I have posted an example here