【发布时间】:2019-08-28 11:54:40
【问题描述】:
我想在点击 td 时为 v-for 中的项目添加一个 css 类
<template>
<div>
<h1>Forces ()</h1>
<section v-if="errored">
<p>We're sorry, we're not able to retrieve this information at the moment, please try back later</p>
</section>
<section v-if="loading">
<p>loading...</p>
</section>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>#</th>
<th>ID</th>
<th
@click="orderByName = !orderByName">Forces</th>
</tr>
<th>Delete</th>
</thead>
<tbody>
<tr v-for="(force, index) in forces" @click="completeTask(force)" :class="{completed: force.done}" v-bind:key="index">
<td>
<router-link :to="{ name: 'ListForce', params: { name: force.id } }">Link</router-link>
</td>
<th>{{ force.done }}</th>
<th>{{ force.name }}</th>
<th><button v-on:click="removeElement(index)">remove</button></th>
</tr>
</tbody>
</table>
<div>
</div>
</div>
</template>
<script>
import {APIService} from '../APIService';
const apiService = new APIService();
const _ = require('lodash');
export default {
name: 'ListForces',
components: {
},
data() {
return {
question: '',
forces: [{
done: null,
id: null,
name: null
}],
errored: false,
loading: true,
orderByName: false,
};
},
methods: {
getForces(){
apiService.getForces().then((data, error) => {
this.forces = data;
this.forces.map(function(e){
e.done = false;
});
this.loading= false;
console.log(this.forces)
});
},
completeTask(force) {
force.done = ! force.done;
console.log(force.done);
},
removeElement: function (index) {
this.forces.splice(index, 1);
}
},
computed: {
/* forcesOrdered() {
return this.orderByName ? _.orderBy(this.forces, 'name', 'desc') : this.forces;
}*/
},
mounted() {
this.getForces();
},
}
</script>
<style>
.completed {
text-decoration: line-through;
}
</style>
我希望在单击时有一条线穿过项目,但 dom 没有更新。如果我进入 chrome 中的 vue 选项卡,我可以看到每个项目的 force.done 更改,但前提是我单击对象并重新单击它。我不确定为什么当我之前使用过点击和 css 绑定时状态没有更新。
【问题讨论】:
-
这听起来像是反应性问题。
forcesOrdered来自哪里?它是在组件data或存储state中的某处定义的吗?您可能想尝试使用this.$set(force, 'done', true)看看是否有效。它没有解决根本问题,但有助于确认这是一个反应性问题。 -
done是这些对象的现有属性还是您将其添加到completeTask中? -
嗨,是的,它是对象中的一个属性
-
forcesOrdered 在计算中
-
试过this.$set(force, 'done', true) 但和以前一样,值更新但屏幕上没有更新