[Vuejs]-How to use array variable for show/collapese control?

1👍

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>

1👍

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://v2.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])

Leave a comment