Home » vue » How to use array variable for show/collapese control?

How to use array variable for show/collapese control?

Posted by: admin November 26, 2021 Leave a comment

Questions:

Trying to use array instead show0 and show1 variables,

<div id="demo2">
  <p>1. <button v-on:click="show[0] = !show[0]">Toggle</button>
    <div class="collapsible" v-show="!show[0]">Hello!</div>
  </p>
  <p>2. <button v-on:click="show[1] = !show[1]">Toggle</button>
    <div class="collapsible" v-show="!show[1]">Hello!</div>
  </p>
</div>

with new Vue({ el:'#demo2', data:{show:[true,true]} })Not working, and no error message.


NOTE. When using simple

  <p>1. <button v-on:click="show0 = !show0">Toggle</button>
     <div class="collapsible" v-show="!show0">Hello!</div>
  </p> ...

and new Vue({ el:'#demo1', data:{show0:true,show1:true} })
it is working fine.

PS: I see complex solutions like this one with template and component… but my aim here is only to understand how to use array.

Answers:

You are changing the show [] using v-on:click="show[0] = !show[0]".

Vue cannot detect these kind of array manipulations. See array change detection caveats.

So use vm.$set() instead as follows

<p>1. <button v-on:click="$set(show, 0, !show[0])">Toggle</button>
  <div class="collapsible" v-show="!show[0]">Hello!</div>
</p>

Or else use array’s splice() method:

<p>1. <button v-on:click="show.splice(0, 1, !show[0])">Toggle</button>
  <div class="collapsible" v-show="!show[0]">Hello!</div>
</p>

###

From Vue 1.0 but the same is applicable to Vue 2.0

When you modify an Array by directly setting an index (e.g. arr[0] =
val) or modifying its length property. Similarly, Vue.js cannot pickup
these changes. Always modify arrays by using an Array instance method,
or replacing it entirely. Vue provides a convenience method
arr.$set(index, value) which is syntax sugar for arr.splice(index, 1,
value).

https://vuejs.org/2016/02/06/common-gotchas/

Here is the syntax you can use:

https://vuejs.org/v2/api/#vm-set

This should work:

v-on:click="$set(show, 0, !show[0])"

I would normally not do this kind of stuff inside of a inline handler though. The complexity will increase too much for a simple template. I would probably do this inside of a method like so:

this.$set(this.show, 0, !this.show[0])