gpt4 book ai didi

javascript - 为什么 Vue.js :class not working when it depends on list item property?

转载 作者:行者123 更新时间:2023-12-03 06:47:36 25 4
gpt4 key购买 nike

我会很矮。这是我的 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处理程序:
  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
},
所以,处理程序正在工作,我看到 products数组已更新 - 我在控制台中看到了这一点。
但是css没有改变。 (如果我更改 .name ,css 会改变 diplay)。
我的 products数组最初看起来像这样: [{name: 'some name'},...]
我很迷惑。我想我误解了一些东西。

已解决,感谢@Ross Allen。
为了使它工作,我需要一些小的改变:
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 => {
...

最佳答案

toWrite是一个新属性,那么 Vue 无法检测到它的添加。见 Vue reactitivy for objects :“Vue 无法检测属性添加或删除”。
我建议处理 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
},

关于javascript - 为什么 Vue.js :class not working when it depends on list item property?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62643731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com