【问题标题】:Vuetify change checkbox icon in v-select / v-comboboxv-select / v-combobox中的Vuetify更改复选框图标
【发布时间】:2021-08-19 21:17:26
【问题描述】:

我使用了 Vuetify,但禁用了所有图标的导入,因为在 Nuxt 中 treeshaking 无法正常工作,而是按照此线程中的说明手动导入它们:vuetifyjs: Adding only used icons to build

但是,这意味着许多需要图标的组件,例如 v-checkbox、v-select 或 v-combobox(在其下拉菜单中使用 v-checkbox)需要手动添加它们的图标。仅使用 v-checkbox 就可以使用 :on-icon 和 :off-icon 道具,但我无法弄清楚当其他组件使用复选框时如何到达它们。 我一直在尝试改变 v-select 和 v-combobox 中的行为。

据我所知,但显然这并没有添加选中图标,只是添加了空白图标。

<v-combobox outlined multiple chips v-model="select" :items="items">
    <template v-slot:item="{ item }">
       <v-icon>{{mdiCheckboxBlankOutline}}</v-icon>{{ item }}
   /template>
</v-combobox>

import { mdiCheckboxBlankOutline, mdiCheckboxMarked } from "@mdi/js";

Data(){
select: ["Stockholm"],
      items: [
        "Stockholm",
        "London",
      ],

}

因此,我的问题是,如何使用导入的图标复制组合框菜单的默认复选框行为? 该线程似乎在谈论它,但从未最终显示代码示例: https://github.com/vuetifyjs/vuetify/issues/10904 (意味着它应该看起来像这样)

【问题讨论】:

    标签: vue.js nuxt.js vuetify.js


    【解决方案1】:

    您可以使用item 插槽(其中为您提供itemonattrs 对象)来复制默认行为。

    您将on(事件)和attrs(属性)对象绑定到自定义列表项,以将单击事件从您的列表项发送到组合框组件。

    接下来,根据所选值设置适当的图标。请参阅下面的代码和代码沙箱。

    <template>
      <v-app>
        <v-combobox
          label="Label"
          outlined
          multiple
          chips
          v-model="select"
          :items="items"
        >
          <template v-slot:item="{ item, on, attrs }">
            <v-list-item v-on="on" v-bind="attrs">
              <v-list-item-icon>
                <v-icon>
                  {{ select.includes(item) ? checkIcon : uncheckIcon }}
                </v-icon>
              </v-list-item-icon>
              <v-list-item-content>
                <v-list-item-title v-text="item" class="text-left"></v-list-item-title>
              </v-list-item-content>
            </v-list-item>
          </template>
        </v-combobox>
      </v-app>
    </template>
    
    <script>
    import { mdiCheckboxBlankOutline, mdiCheckboxMarked } from "@mdi/js";
    export default {
      name: "HelloWorld",
      data() {
        return {
          items: ["One", "Two", "Three"],
          select: [],
          uncheckIcon: mdiCheckboxBlankOutline,
          checkIcon: mdiCheckboxMarked,
        };
      },
    };
    </script> 
    

    代码沙盒:https://codesandbox.io/s/recursing-banach-cb7ys?file=/src/components/HelloWorld.vue

    【讨论】:

    • 效果很好,您有没有机会详细说明绑定 attrs 的实际作用?本质上 v-bind="attrs" 设置数据绑定到底是什么?
    • v-bind="attrs" 基本上是为选定的列表项设置默认样式(背景、颜色),因此您不必手动设置它们。
    猜你喜欢
    • 2022-07-02
    • 1970-01-01
    • 2020-02-10
    • 2021-11-22
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多