首页 > 解决方案 > 带有开关或复选框的 Vuetify 表

问题描述

我想使用 v-data-table 为最终用户打开和关闭权限以接收通知。

我有两个单独的问题,第二个是在我的代码笔中试图重新创建可能突出我对该问题的误解的问题。我在下面列出了两个。包含 Codepen 以复制我的 UAT 代码。

我的项目最初是在 2019 年初部署的,目前正在使用“vuetify”:“^1.5.18”,这可以解释为什么我无法使用“vuetify”:“^2.2.11”使其工作。

  1. 我有一个部署到开发/生产环境的版本。我要解决的问题是为什么我在数据表中的开关在单击开关的圆圈部分时没有改变,两边都更新得很好。在数据表之外,Switch 按预期工作。这不是最大的问题,但不喜欢它作为用户体验,因为您期望只需单击开关即可更新。 在此处输入图像描述

  2. 我尝试重新创建问题以演示使用 codepen 并遇到第二个问题,即此处的开关不会显示在数据表中。这让我感到不舒服,因为我不了解最终的行为。 密码笔

      <v-data-table
          :headers="headers"
          :items="listItems"
          class="elevation-2"
        >
        <template slot="items" slot-scope="props">
          <tr>
            <td>{{props.item.label}}</td>
            <td>
              <v-switch
                v-model="props.item.switch"
                @click="details(props.item.label, !props.item.switch)"
              ></v-switch>
            </td>
            <td>
              <v-checkbox
                  v-model="props.item.switch"
                  label="Test"
                  @click="details(props.item.label, !props.item.switch)"
              >
              </v-checkbox>
            </td>
    
          </tr>
        </template>
      </v-data-table>
    
    </v-container>
    

标签: vue.jsvuejs2vue-componentvuetify.jsv-data-table

解决方案


问题是您的模板标签语法。

这就是您在 v-data-table 中编写插槽模板的方式

<template slot="item.switch" slot-scope="{ item }">
    <v-switch v-model="item.switch"></v-switch>
</template>

修复此问题后,您既不需要开关或复选框上的单击事件,也不需要方法“详细信息”。使用 v-model 就足够了。

这是组件的完整代码,以造福所有人

<template>
    <v-container class="px-0" fluid>
        <v-data-table :headers="headers" :items="listItems" class="elevation-2">
            <template slot="item.switch" slot-scope="{ item }">
                <v-switch v-model="item.switch"></v-switch>
            </template>
            <template slot="item.checkbox" slot-scope="{ item }">
                <v-checkbox v-model="item.switch" :label="item.switch"></v-checkbox>
            </template>
        </v-data-table>
    </v-container>
</template>

<script>
    export default {
        props: ["car"],
        data() {
            return {
                switch1: true,
                listItems: [
                    { label: 0, switch: false },
                    { label: 1, switch: true },
                    { label: 2, switch: true }
                ],
                headers: [
                    { text: 'Label', sortable: false, value: 'label' },
                    { text: 'Switch', sortable: false, value: 'switch' },
                    { text: 'Checkbox', sortable: false, value: 'checkbox' },
                ]
            }
        },

        methods: {
        },
    };
</script>

祝你好运。


推荐阅读