首页 > 解决方案 > 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"
        }
    ]
}

有人可以解释这种行为和/或告诉我如何解决这个问题吗?

标签: javascriptarraysvue.jsvuetify.js

解决方案


我想知道为什么 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>

推荐阅读