如何在VueJS中创建类似Vuetify v-list-item-title的插槽包裹组件?
如何创建Vuetify v-list-item的append插槽包裹组件
在Vuetify中,<v-list-item>组件提供了append、prepend、subtitle、title等插槽。官方配套的<v-list-item-title>和<v-list-item-subtitle>组件,可以替代繁琐的<template #title>/<template #subtitle>写法,让开发者无需手动创建模板标签,就能直接把内容传入对应插槽。
简化写法示例
<v-list> <v-list-item v-for="(item, index) in [1, 2, 3]" :key="index" :value="index"> <v-list-item-title> Title: {{ item }} </v-list-item-title> <v-list-item-subtitle> Subtitle: {{ item }} </v-list-item-subtitle> 默认内容 </v-list-item> </v-list>
传统模板插槽写法(对比)
<v-list> <v-list-item v-for="(item, index) in [1, 2, 3]" :key="index" :value="index"> <template #title> Title: {{ item }} </template> <template #default> 默认内容 </template> <template #subtitle> Subtitle: {{ item }} </template> </v-list-item> </v-list>
那么,如何创建一个类似<v-list-item-title>的组件,用来包裹append插槽的内容呢?
实现方案
核心思路是利用Vue的插槽传递机制,让自定义组件自动将内部内容注入到父级<v-list-item>的append插槽中,具体步骤如下:
1. 编写自定义组件 VListItemAppend
新建组件文件(如VListItemAppend.vue),代码非常简洁:
<template> <template v-slot:append> <slot /> </template> </template> <script setup> // 无需额外逻辑,仅负责将内部内容传递到父级的append插槽 </script>
2. 在项目中使用该组件
注册组件后,即可像使用官方组件一样,直接在<v-list-item>内部使用:
<template> <v-list> <v-list-item v-for="(item, index) in [1, 2, 3]" :key="index" :value="index"> <v-list-item-title> Title: {{ item }} </v-list-item-title> <!-- 自定义的append插槽组件 --> <v-list-item-append> <v-icon>magnify</v-icon> </v-list-item-append> 列表项默认内容 </v-list-item> </v-list> </template> <script setup> import VListItemAppend from './VListItemAppend.vue' </script>
原理说明
这个自定义组件的工作逻辑和Vuetify官方的<v-list-item-title>完全一致:组件内部通过v-slot:append声明插槽,当它作为<v-list-item>的子组件时,Vue会自动识别这个命名插槽,并将组件内部的内容传递给父组件的append插槽,从而省去手动编写<template #append>的步骤。
内容的提问来源于stack exchange,提问作者FieryRider
相关产品推荐
相关产品推荐

