hamidreza nikoonia
hamidreza nikoonia

Reputation: 2165

Ability to toggle True/False with ( v-if ) in the loop

I am asking about hiding and showing an element in Vue.js

I always use this

<ele v-if="value" />

and then set {value} in Vue Instance data object, then toggle True/False for toggle visible, but now in my situation , my v-if condition put in some element , then this element create with v-for directive

some thing like this

<div v-for="item in items" >
 <ele v-if="value" :key="item.i" />
 <ele v-if="value" :key="item.i" />
 <ele v-if="value" :key="item.i" />

     // this button fire a method for Change (toggle) value (used for v-if)
   <button @click="ToggleValue" > update </button>
</div>

In my view i have a table contain some rows and each rows have some field ( all field have v-if directive ) and in each rows we have button for fire method

Now what is my question ?!!

At the end my table is doing this , when click on every button ToggleValue method execute and toggle value of (value) object , now all field in all rows change the value ( all thing doing right :D )

but I want click on every button in each row just change the value of that row

I have dummy way

< ele v-if="value(item.id)" />
.........
.........
<button @click="ToggleValue(itme.id)" > 

if my index of loop is Const and static I use this way , but now items in loop are dynamic

all thing was in my pen at here , thanks for give me your time

https://codepen.io/hamidrezanikoonia/pen/OQGrPB?editors=1100

Upvotes: 1

Views: 10213

Answers (1)

acdcjunior
acdcjunior

Reputation: 135832

Instead of having a single value, turn value into an object (or array) and index it by item.id.

Updated codepen: https://codepen.io/acdcjunior/pen/MQRZmK?editors=1010

In your pen, the JavaScript:

    ...
    ],
    update_:false
  },
  methods: {
    set_update() {
      this.update_ = !this.update_;
    }
  }

becomes:

    ...
    ]
    update_: {1: false, 2: false, 3: false}
  },
  methods: {
    set_update(id) {
      this.update_[id] = !this.update_[id];
    }
  }

And the template:

<td :key="getValue.id+4" v-if="update_" mode="in-out" >  {{ getValue.rate_curr }} </td>
...
<button @click="set_update()" type="button" class="btn btn-primary">  Update </button>

becomes:

<td :key="getValue.id+4" v-if="update_[getValue.id]" mode="in-out" >  {{ getValue.rate_curr }} </td>
...
<button @click="set_update(getValue.id)" type="button" class="btn btn-primary">  Update </button>

Upvotes: 3

Related Questions