在大学里,我必须创建一个管理家庭自动化的Vue.js应用程序。后端是一个简单的json服务器。该服务器包含每个房间的数据,包括时隙。
时隙确定房间中某一元素在两个时间点之间的值(例如温度)。
我使用v-data-table来显示特定房间、特定元素的每个时间段。由于对应于窗帘位置的时隙的值是一个布尔值,因此我想在表中将true或false替换为open或closed。我试图通过将时隙数组传递给数组映射函数来实现这一点,但是这导致了一些奇怪的行为。
首先:在新数组中,时隙值总是'open‘,当值为false时也是如此。其次:在我的json服务器中,时隙的值实际上变成了'open‘。我不知道为什么会发生这种情况,因为我认为map函数会返回一个全新的数组,而不是更改当前的数组。
数据表:
<v-data-table
v-if="room"
:headers="headers"
:items="room.timeslots.filter(timeslot => {return timeslot.element == 'cur'}).map(timeslot => {if(timeslot.value) {timeslot.value='open'} else {timeslot.value='gesloten'} return timeslot;})"
:custom-sort="customSort"
hide-default-footer
class="elevation-1 ma-5"
>
<template v-slot:[`item.actions`]="{ item }">
<v-icon @click="deleteTimeslot(item.id)">mdi-delete</v-icon>
</template>
<template slot="no-data">
Voor dit element zijn er nog geen tijdssloten ingesteld.
</template>
</v-data-table>来自我的json服务器的示例数据:
{
rooms: [
{
"id": 2,
"name": "Bureau",
"description": "Ssssssst, hier wordt gewerkt!",
"temp": 22,
"curtainsOpen": true,
"volume": 11,
"light": 0,
"floor": 1,
"x": 0,
"y": 0,
"width": 350,
"height": 350,
"timeslots": [
{
"id": 1,
"start": "12:00",
"end": "13:00",
"value": "21",
"element": "temp"
},
{
"id": 4,
"start": "03:20",
"end": "04:20",
"value": true,
"element": "cur"
},
{
"id": 5,
"start": "14:00",
"end": "15:00",
"value": false,
"element": "cur"
}
]
}有人能解释一下这个行为和/或告诉我如何解决这个问题吗?
发布于 2020-11-12 23:44:20
我想知道为什么map方法表现得像一个变异方法,而它实际上是一个非变异方法。
这是因为我使用它作为一种变异方法,这当然是不好的做法。
下面是一个可行的解决方案:
<v-data-table
v-if="room"
:headers="headers"
:items="room.timeslots.filter(timeslot => {return timeslot.element == 'cur'}).map(timeslot => {return {...timeslot, value: timeslot.value ? 'open' : 'closed'}})"
:custom-sort="customSort"
hide-default-footer
class="elevation-1 ma-5"
>
<template v-slot:[`item.actions`]="{ item }">
<v-icon @click="deleteTimeslot(item.id)">mdi-delete</v-icon>
</template>
<template slot="no-data">
Voor dit element zijn er nog geen tijdssloten ingesteld.
</template>
</v-data-table>https://stackoverflow.com/questions/64802428
复制相似问题