[Vuejs]-Binding to array not working within vue instance

0👍

Try this:

HTML:

<div id="app">

  <div class="block">
    <button @click.prevent="mytoggle(0)">block one</button>
    <div v-show="boxes[0].show">
      <p>i am box number one</p>
      <p>i am box number one</p>
    </div>
  </div>

  <div class="block">
    <button @click.prevent="mytoggle(1)">block two</button>
    <div v-show="boxes[1].show">
      <p>i am box number two</p>
      <p>i am box number two</p>
    </div>
  </div>

  <div class="block">
    <button @click.prevent="mytoggle(2)">block three</button>
    <div v-show="boxes[2].show">
      <p>i am box number three</p>
      <p>i am box number three</p>
    </div>
  </div>

  <hr/>

  <pre>{{ boxes | json}}</pre>

</div>

Vue:

var vm = new Vue({
    el: '#app',
    data: {
        boxes: [{show:false},{show:true},{show:false}]
    },
    methods: {
        mytoggle: function (n) {  
            for(var i = 0; i < 3; i++) { // close all boxes
                vm.boxes[i].show = false;
            }
            vm.boxes[n].show = true; // open the corresponding box
        }
    }
});

Fiddle:
https://jsfiddle.net/crabbly/9a6bua6x/

EDIT:

You could also just change your mytoggle method to change array values using Vue’s $set:

mytoggle: function (n, event) {
    event.preventDefault();
    for(var i = 0; i < 3; i++) { // close all boxes
        this.boxes.$set(i, false);
    }
    this.boxes.$set(n, true); // open the corresponding box
    console.log(n);
}

0👍

You should use the $set method, instead of directly change. [ref]

Also, you could use a simpler workaround like this:

new Vue({
  el: '#app',
  data: {
    selected: 1
  },
  methods: {
    select (index) {
      this.selected = index
    },
    isSelected (index) {
      return this.selected === index
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.24/vue.min.js"></script>

<div id="app">
  <div class="block">
    <button @click="select(0)">block one</button>
    <div v-show="isSelected(0)">
      <p>i am box number one</p>
      <p>i am box number one</p>
    </div>
  </div>

  <div class="block">
    <button @click="select(1)">block two</button>
    <div v-show="isSelected(1)">
      <p>i am box number two</p>
      <p>i am box number two</p>
    </div>
  </div>

  <div class="block">
    <button @click="select(2)">block three</button>
    <div v-show="isSelected(2)">
      <p>i am box number three</p>
      <p>i am box number three</p>
    </div>
  </div>
</div>

Leave a comment