0

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>
1
  • 1
    toggling the array elements will not make this.grid reactive. You have to assign the whole this.grid on toggle to make it reactive. You can use this.grid.$set(index, val) or you can also use this let tempArray[]; tempArray = this.grid; tempArray[targetPosition] = value; this.grid = tempArray; Commented Jul 7, 2022 at 13:15

1 Answer 1

1

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?)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.