Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue v-if can't access booleans in arrays

I created a vue component with the following data:

data: function () {
    return {
        hwshow: [false, false, false, false, false, false, false, false, false, false],
    };
},

And a method to switch these values:

methods: {
    fliphw: function (index) {
        this.hwshow[index] = !this.hwshow[index];
        console.log(this.hwshow);
    },
},

in the html I have

<li v-show="hwshow[0]">foo bar</li>

I know the fliphw function is being called (because of the console.log), but when the value of hwshow[0] is true foo bar still isn't appearing. When I switch to using a boolean, instead of an array of boolean it works. Why? If I can't access an array of booleans what other solutions to the problem might there be?

like image 976
Joseph Summerhays Avatar asked Jan 27 '23 18:01

Joseph Summerhays


1 Answers

Why isn't the DOM updating?, this is a common gotcha:

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.

To overcome this limitation triggering state updates in the reactivity system you can use Vue.set

new Vue({
  el: '#app',
    data: function () {
      return {
        hwshow: [false, false, false, false, false, false, false, false, false, false],
      };
    },
    methods: {
      fliphw: function (index) {
        this.$set(this.hwshow, index, !this.hwshow[index])
    },
  },
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <span @click="fliphw(0)">click to flip</span>
  
  <div>
   {{ hwshow }}
  </div>
  
  <ul>
     <li v-show="hwshow[0]">foo bar</li>
  </ul>
</div>
like image 69
Paolo Avatar answered Feb 08 '23 23:02

Paolo