Razvan Nuna
Razvan Nuna

Reputation: 35

Variable in Vue.js is not reactive

Why is my grid variable not reactive? In the toggle(index) method, after the logic, the console.log(this.grid) is printing the correct output but the grid variable isn't updating

<template>
  <div class="game-container">
  
    <div>{{ grid }}</div>

    <div class="board">
      <div 
        @click="toggle(index)" 
        ref="squares" 
        v-for="(item, index) in grid" 
        :key="index" 
        class="square" 
        :class="{ 'on': item }">
        {{ item }} {{ index }}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'GameComponent',
  data() {
    return {
      size: 5,
      grid: Array(25).fill(true),
    }
  },
  methods: {
    toggle(index) {
      const C = index
      const N = index - this.size >= 0 ? index - this.size : null
      const E = (index + 1) % this.size != 0 ? index + 1 : null
      const S = index + this.size < this.size * this.size ? index + this.size : null
      const W = index % this.size != 0 ? index - 1 : null

      this.grid[C] = !this.grid[C]
      if (N) this.grid[N] = !this.grid[N]
      if (E) this.grid[E] = !this.grid[E]
      if (S) this.grid[S] = !this.grid[S]
      if (W) this.grid[W] = !this.grid[W]

      console.log(this.grid)
    }
  }
}
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  height: 100%;
}

body {
  height: 100%;
}

.game-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.board {
  display: flex;
  flex-wrap: wrap;
  width: 40rem;
}

.square {
  width: 8rem;
  height: 8rem;
  border: 2px solid red;
  cursor: pointer;
}

.on {
  background-color: black;
  color: white;
}

.hover {
  background-color: orange;
}
</style>

Upvotes: 0

Views: 629

Answers (1)

creage
creage

Reputation: 190

Arrays in Vue are not reactive by design. It is well documented https://v2.vuejs.org/v2/guide/reactivity.html#For-Arrays, with solutions.

But who reads manuals these days, right?)

Upvotes: 1

Related Questions