【问题标题】:Variable in Vue.js is not reactiveVue.js 中的变量不是反应式的
【发布时间】:2022-07-09 14:54:59
【问题描述】:

为什么我的grid 变量没有反应?在toggle(index) 方法中,之后 逻辑上,console.log(this.grid) 正在打印正确的输出,但 grid 变量没有更新

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

【问题讨论】:

  • 切换数组元素不会使this.grid 反应。您必须在切换时分配整个 this.grid 以使其具有反应性。你可以使用this.grid.$set(index, val) 或者你也可以使用这个let tempArray[]; tempArray = this.grid; tempArray[targetPosition] = value; this.grid = tempArray;

标签: vue.js vuejs2


【解决方案1】:

Vue 中的数组在设计上不是反应式的。这是有据可查的https://v2.vuejs.org/v2/guide/reactivity.html#For-Arrays,有解决方案。

但是现在谁在看手册,对吧?)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-28
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2023-01-19
    • 2015-06-25
    • 1970-01-01
    • 2016-09-18
    相关资源
    最近更新 更多