v-bind 没有检测到数组内容的变化(vue js)

v-bind isn't detecting the change in array content (vue js)

我正在尝试在用户单击按钮后更改图像的 id。最初,元素的 id 应为 B0_h,但在用户单击按钮后,数组中的值应更改为 true.最初所有的数组值都是 false,但是一旦数组中元素的值变为真,id 应该变为 B0_v

使用 Vue 开发工具,我注意到数组中的值正在按预期变化,但是,v-bind 无法检测到这种变化。从v-bind的角度来看,B[0]的价值仍然是false。结果,id仍然是B0_h

这是我的模板:

<template>
    <div>
       <button type="button" id="button0" v-on:click="toggle('B0')"></button>
       <img src="../assets/img1.png" alt="A" v-bind:id="[A[0] === true ? 'A0_v' : 'A0_h']" >
       <img src="../assets/img2.png" alt="B" v-bind:id="[B[0] === true ? 'B0_v' : 'B0_h']">
    </div>
</template>

这是我的脚本:

<script>
export default {
  name: 'Demo',
  props: {},
  data: function(){
      return{
          A: [false,false,false,false,false,false,false,false,false],
          B: [false,false,false,false,false,false,false,false,false],
          playerTurn: true;
      }
  },
  methods: 
  {
    toggle(x)
    {
      if(x == 'B0' && this.playerTurn)
      {
        this.B[0] = true;
      }
    }
  }
}
</script>

知道我在这里做错了什么吗?

这是由于 Vue 对数组和对象的变化的处理。 Vue 不会跟踪您所做的更改。为此,它提供了一种特殊的方法:set。它有 3 个参数:必须更改的数组(或对象)、索引和应设置的值。

在您的示例中,它将如下所示:

Vue.set(this.B, 0, true);

用这行代替:

this.B[0] = true;

更多信息请查看官方documentation。这是一个简短的摘录:

Vue.set( target, propertyName/index, value ) Arguments:

  • {Object | Array} target
  • {string | number} propertyName/index
  • {any} value

Returns: the set value.

Usage:

Adds a property to a reactive object, ensuring the new property is also reactive, so triggers view updates. This must be used to add new properties to reactive objects, as Vue cannot detect normal property additions (e.g. this.myObject.newProperty = 'hi').