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

标签 javascript html vue.js vuejs2

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

使用 Vue 开发工具,我注意到数组中的值正在按预期变化,但是,v-bind 无法检测到这种变化。从v-bind 的 Angular 来看,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').

关于javascript - v-bind 没有检测到数组内容的变化(vue js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58587450/

相关文章:

vue.js - 父级在 Vuejs 中监听子级发出事件

javascript - 返回 null mysql nodejs

javascript - 更新时文件上传不会移动到文件夹中

javascript - 未选中复选框时无法从第二个表中删除行

html - Bootstrap 显示 flex 高度

javascript - 将VueJS与Axios一起使用后响应数据消失

javascript - 如何修复 "BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default"错误?

javascript - 为什么用户/代理不能选择电子邮件地址或号码?

javascript - 我可以将这个循环数组转换为 Json 对象吗?

javascript - 在 Angular 中首次渲染后如何打破数据绑定(bind)?