简体   繁体   English

为什么 Vue.js:class 在依赖于列表项属性时不起作用?

[英]Why Vue.js :class not working when it depends on list item property?

I'll be short.我会很短。 Here is my html:这是我的 html:

<tr v-for="product in products"
:class="{'bg-red': product.toWrite }" :key="product.name">
  <td @click="setObjectToWrite(product.name)" class="show-hover">
    <u>{{product.name}}</u>
  </td>
</tr>

@onclick handler: @onclick处理程序:

  setObjectToWrite (name) {
    // this.products = []
    let products = this.products
    products.forEach(p => {
      if (p.name == name) {
        p.toWrite = true // ignores
        p.name+=' ' // now displays
      }
    })
    console.log('new products', products) // OK
    this.products = products
  },

So, the handler is working, I see that products array is updated - I see this in console.因此,处理程序正在工作,我看到products数组已更新 - 我在控制台中看到了这一点。 But the css is not changing.但是 css 没有改变。 (If I change .name , css does diplay changes). (如果我更改.name , css 会更改显示)。

My products array initially looks like this: [{name: 'some name'},...]我的products数组最初看起来像这样: [{name: 'some name'},...]

I am confused.我很困惑。 I think I misunderstood something.我想我误解了什么。


Solved, thanks to @Ross Allen.解决了,感谢@Ross Allen。 To make it work, I need some minor changes:为了使它工作,我需要一些小的改动:

setObjectToWrite (product) {
    let name = product.name
    let products = [...this.products] // we should treat data-props as immutable, if we need to add props to objects.
    products.forEach(p => {
    ...

If toWrite is a new property then Vue cannot detect its addition.如果toWrite是一个新属性,那么 Vue 无法检测到它的添加。 See Vue reactitivy for objects : "Vue cannot detect property addition or deletion".请参阅对象的 Vue 反应性:“Vue 无法检测属性添加或删除”。

I suggest treating values in data as immutable, and for this case that would mean creating new objects whenever you need to add properties:我建议将data中的值视为不可变的,对于这种情况,这意味着在需要添加属性时创建新对象:

  setObjectToWrite (name) {
    const nextProducts = this.products.map(p => {
      if (p.name == name) {
        // Creates a new Object, Vue will see this and re-render
        return {
          ...p,
          toWrite: true,
        };
      } else {
        return p;
      }
    })
    this.products = nextProducts
  },

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

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