gpt4 book ai didi

javascript - 绑定(bind)到对象的 Vue.js 类在对象更新时不会更改

转载 作者:行者123 更新时间:2023-12-02 23:26:49 25 4
gpt4 key购买 nike

我有许多按钮,是使用 v-for 指令生成的。它们都有初始类,基于对象的字符串。我有一个事件,即在单击按钮时更改此字符串。但该类没有更新。我做错了什么?

<template>
<v-layout>
<v-btn v-for="cell in cells" :key='cell.id' v-bind:class='cell.color'
v-on:click='click(cell.id)'>
<p v-if="cell.win">win</p>
<p>{{cell.id}}</p>
</v-btn>
</v-layout>
</template>

<script>

export default {
data: () => {
return {
cells: {

},
winId: 0,
}
},
methods: {
generateCells() {
this.winId = Math.floor(Math.random() * 100);
for (var i = 0; i < 100; i++) {
this.cells[i] = {
id: i,
color: 'info'
}
}
},
click(id) {
if (this.cells[id] == this.winId) {
alert('you win');
this.cells[id].color = 'success';
} else {
this.cells[id].color = 'warning';
}
}
},
created() {
this.generateCells();
}
}

</script>

我希望按钮类在受尊重的对象更新时进行更新。对象 .color 属性已更新,但类仍保持初始状态。

最佳答案

Due to the limitations of modern JavaScript (and the abandonment of Object.observe), Vue cannot detect property addition or deletion. Since Vue performs the getter/setter conversion process during instance initialization, a property must be present in the data object in order for Vue to convert it and make it reactive.

在此处了解更多信息:Reactivity in Depth .

Vue 提供了一个 API 来向嵌套级别对象添加属性并使它们具有响应性。

为此,您可以使用

Vue.set(object, propertyName, value);

您还可以使用vm.$set方法

this.$set(this.someObject, 'b', 2);

因此,在您的代码中,您需要设置数组的值

this.$set(this.cells, i, {
id: i,
color: 'info'
});

请参阅下面的完整代码片段:

window.onload = () => {
new Vue({
el: '#app',
data: () => {
return {
cells: {

},
winId: 0,
}
},
methods: {
generateCells() {
this.winId = Math.floor(Math.random() * 100);
for (var i = 0; i < 100; i++) {
this.$set(this.cells, i, {
id: i,
color: 'info'
})
}
},
click(id) {
if (this.cells[id] == this.winId) {
alert('you win');
this.cells[id].color = 'success';
} else {
this.cells[id].color = 'warning';
}
}
},
created() {
this.generateCells();
}
})
}
body {
padding: 1rem;
}

.info {
color: blue;
}

.warning {
color: red;
}

.success {
color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
<v-layout>
<v-btn v-for="cell in cells" :key='cell.id' v-bind:class='cell.color' v-on:click='click(cell.id)'>
<p v-if="cell.win">win</p>
<p>{{cell.id}}</p>
</v-btn>
</v-layout>
</div>

关于javascript - 绑定(bind)到对象的 Vue.js 类在对象更新时不会更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56698815/

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