Q: vue 的 vnode 如何渲染到 template 里?

2022-12-28 12:33:05 +08:00
 anonymous2351d00

intro

有如下工具类,返回了一个 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
  };
};

question

在我的组件里使用了这个函数

  const icon = useIconRender();
  const node = icon.iconRender({ icon: "ant-design:vertical-left" });

可是我要怎么把这个东西渲染到页面上呢?

1434 次点击
所在节点    Vue.js
7 条回复
Li83Xi7Gai4
2022-12-28 12:37:45 +08:00
```
components: {
Icon: {

}
}
```
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 });
}
}
}
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 />
anonymous2351d00
2022-12-28 13:42:38 +08:00
@Li83Xi7Gai4 意思就是封装成一个组件吗?
lwc645089781
2022-12-28 13:54:12 +08:00
用这个吧
<component :is="vnode"></component>
anonymous2351d00
2022-12-28 15:59:06 +08:00
@lwc645089781 我试一下看看
admc
2022-12-28 16:47:41 +08:00
页面里引入该函数,注册为组件,然后直接用就行了,典型的函数式组件用法。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/905119

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX