有如下工具类,返回了一个 render 函数使用h
创建了vnode
import { h } from 'vue'; import SvgIcon from '@/components/custom/SvgIcon.vue'; /** * 图标渲染 * - 用于 vue 的 render 函数 */ export const useIcOnRender= () => { interface IconConfig { /** * 图标名称(iconify 图标的名称) * - 例如:mdi-account 或者 mdi:account */ icon?: string; /** * 本地 svg 图标文件名(assets/svg-icon 文件夹下) */ localIcon?: string; /** 图标颜色 */ color?: string; /** 图标大小 */ fontSize?: number; } interface IconStyle { color?: string; fontSize?: string; } /** * 图标渲染 * @param config * @property icon - 图标名称(iconify 图标的名称), 例如:mdi-account 或者 mdi:account * @property localIcon - 本地 svg 图标文件名(assets/svg-icon 文件夹下) * @property color - 图标颜色 * @property fontSize - 图标大小 */ const icOnRender= (config: IconConfig) => { const { color, fontSize, icon, localIcon } = config; const style: IcOnStyle= {}; if (color) { style.color = color; } if (fontSize) { style.fOntSize= `${fontSize}px`; } if (!icon && !localIcon) { window.console.warn('没有传递图标名称,请确保给 icon 或 localIcon 传递有效值!'); } return () => h(SvgIcon, { icon, localIcon, style }); }; return { iconRender }; };
在我的组件里使用了这个函数
const icon = useIconRender(); const node = icon.iconRender({ icon: "ant-design:vertical-left" });
可是我要怎么把这个东西渲染到页面上呢?
![]() | 1 Li83Xi7Gai4 2022-12-28 12:37:45 +08:00 ``` components: { Icon: { } } ``` |
![]() | 2 Li83Xi7Gai4 2022-12-28 12:39:59 +08:00 ![]() components: { Icon: { props: { icon: { required:true, type: String, } }, render(h) { return icon.iconRender({ icon: this.icon }); } } } |
![]() | 3 shakukansp 2022-12-28 12:59:26 +08:00 vue 不是 react, template 里的标签必须得是一个组件才能用,所以你不能直接把 render 函数用在 template 里 return defineComponent({ render() { return () => h(SvgIcon, { icon, localIcon, style }); } }) script setup const Icon = useIconRender() template <Icon /> |
4 anonymous2351d00 OP @Li83Xi7Gai4 意思就是封装成一个组件吗? |
5 lwc645089781 2022-12-28 13:54:12 +08:00 用这个吧 <component :is="vnode"></component> |
6 anonymous2351d00 OP @lwc645089781 我试一下看看 |
![]() | 7 admc 2022-12-28 16:47:41 +08:00 页面里引入该函数,注册为组件,然后直接用就行了,典型的函数式组件用法。 |