Vue vuetify 3插槽无法正常使用图标

qjp7pelc  于 2023-04-12  发布在  Vue.js
关注(0)|答案(2)|浏览(299)

当用槽 Package v图标时,它呈现的是文本而不是图标。

<v-icon>myprefix-plus</v-icon><!--works, renders an icon -->
<Icon>myprefix-plus</Icon> <!--renders a text -->

结果如下:

图标组件的实现非常简单:

<template>
  <v-icon><slot></slot></v-icon>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Icon",
});
</script>

为什么它不与插槽工作,我怎么能让它工作,不改变项目中的图标组件的每一个出现?

rsaldnfx

rsaldnfx1#

我想,要实现它,你必须使用Vue Render Functionsh()resolveComponent()
就像IconSlot一样

const IconSlot = {
  setup(props, {slots}) {    
    const vIcon = resolveComponent('v-icon');
    return () => h(vIcon, null, slots.default());
  }
}

我最好在props上执行,就像IconProp一样

const IconProp = {
  props: ['icon'],
  template: `<v-icon :icon="icon"></v-icon>`
}

然后

<icon-prop icon="mdi-vuetify"></icon-prop>

这里是操场

const { createApp, h, resolveComponent } = Vue;
const { createVuetify } = Vuetify;

const Icon = {
  template: `<v-icon><slot></slot></v-icon>`
}

const IconProp = {
  props: ['icon'],
  template: `<v-icon :icon="icon"></v-icon>`
}

const IconSlot = {
  setup(props, {slots}) {    
    const vIcon = resolveComponent('v-icon');
    return () => h(vIcon, null, slots.default());
  }
}

const App = { components: { Icon, IconProp, IconSlot } }

const vuetify = createVuetify();
const app = createApp(App);
app.use(vuetify);
app.mount('#app');
#app { line-height: 3; }
[v-cloak] { display: none; }
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/vuetify@3.1.4/dist/vuetify.min.css" />
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@5.x/css/materialdesignicons.min.css" rel="stylesheet" />
<div id="app">
  1. v-icon: <v-icon icon="mdi-vuetify"></v-icon><br/>
  2. icon: <Icon>myprefix-plus</Icon> <br/>
  3. icon-prop: <icon-prop icon="mdi-vuetify"></icon-prop><br/>
  4. icon-slot: <icon-slot>mdi-vuetify</icon-slot> 
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@3.1.4/dist/vuetify-labs.min.js"></script>
dpiehjr4

dpiehjr42#

可以通过执行其render函数来获取默认插槽的内容:

import { useSlots } from 'vue'

const iconName = useSlots().default()[0].children

看看Vuetify的VIcon是如何做到的。

相关问题