简体   繁体   English

数据作为对象使用时不会更新,但作为变量时会正常更改

[英]Data is not updated when using as object, but changes normally when it's a variable

I'm writing a function to update a custom checkbox when clicked (and I don't want to use native checkbox for some reasons).我正在编写一个函数来在单击时更新自定义复选框(出于某些原因,我不想使用本机复选框)。

The code for checkbox is复选框的代码是

<div class="tick-box" :class="{ tick: isTicked }" @click="() => isTicked = !isTicked"></div>

which works find.哪个作品找到。

However, there are so many checkboxes, so I use object to keep track for each item.然而,有很多复选框,所以我使用对象来跟踪每个项目。 It looks like this看起来像这样

<!-- (inside v-for) -->
<div class="tick-box" :class="{ tick: isTicked['lyr'+layer.lyr_id] }" @click="() => {
  isTicked['lyr'+layer.lyr_id] = !isTicked['lyr'+layer.lyr_id]
}"></div>

Now nothing happens, no error at all.现在什么都没有发生,根本没有错误。

When I want to see isTicked value with {{ isTicked }} , it's just shows {} .当我想用{{ isTicked }}查看isTicked值时,它只显示{}

This is what I define in the <script></script> part.这是我在<script></script>部分定义的。

export default {
  data() {
    return {
      isTicked: {},
      ...
    };
  },
  ...
}

Could you help me where I get it wrong?你能帮我哪里出错吗?

Thanks!谢谢!

Edit:编辑:

I know that declaring as isTicked: {} , the first few clicks won't do anything because its proerty is undefined.我知道声明为isTicked: {} ,前几次点击不会做任何事情,因为它的属性是未定义的。 However, it should be defined by the first/second click not something like this.但是,它应该由第一次/第二次点击来定义,而不是像这样。

Objects does not reflect the changes when updated like this.像这样更新时,对象不会反映更改。 You should use $set to set object properties in order to make them reactive.您应该使用 $set 来设置对象属性,以使它们具有反应性。 Try as below尝试如下

   <div class="tick-box" :class="{ tick: isTicked['lyr'+layer.lyr_id] }" @click="onChecked"></div>

Add below method:添加以下方法:

onChecked() {
  this.$set(this.isTicked,'lyr'+this.layer.lyr_id, !this.isTicked['lyr'+this.layer.lyr_id])
}

VueJS watches data by reference so to update object in state you need create new one. VueJS 通过引用监视数据,以便在需要创建新对象的状态下更新对象。

onChecked(lyr_id) {
    const key = 'lyr'+lyr_id;
    this.isTicked = {...this.isTicked, [key]: !this.isTicked[key]};
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM