javascript - Vuejs 中的意外反应
问题描述
对于大学,我必须创建一个管理家庭自动化的 Vue.js 应用程序。后端是一个简单的 json 服务器。该服务器包含每个房间的数据,包括时间段。
时隙确定两个时间点之间房间中某个元素的值(例如温度)
我正在使用 v-data-table 来显示特定房间和特定元素的每个时间段。由于与窗帘位置相对应的时间段的值是布尔值,因此我想在表中将 true 或 false 替换为 open 或 close 。我试图通过数组映射函数传递时隙数组来做到这一点,但这会导致一些奇怪的行为。
首先:时隙值在新数组中始终为“打开”,当该值为 false 时也是如此。其次:时隙值实际上在我的 json 服务器中更改为“打开”。我不知道为什么会发生这种情况,因为我认为 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"
}
]
}
有人可以解释这种行为和/或告诉我如何解决这个问题吗?
解决方案
我想知道为什么 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>
推荐阅读
- php - 使用 .htaccess 为多语言站点重写 URL(多个变量)
- r - r - 在列表的任何元素中查找字符串,然后使用该列表元素的名称
- haskell - Haskell中的函数类型签名而不使用解释器
- c++ - 将复杂参数列表与类模板一起使用
- java - 在 Java 中设置不同的驻留堆大小和总换出的虚拟内存大小
- structured-data - Google结构化数据测试工具和微格式hcard的问题
- html - 找不到 Django 全局静态文件
- java - 您将如何重构 Arrays.copyOf() 方法以删除 @SuppressWarnings("unchecked") 注释?
- java - 警报对话框仅模糊部分屏幕
- security - Oauth 2 流程:AWS Cognito 的 id_token 是否应该传递给浏览器进行会话管理?