vue3 h函数初体验

定义

创建虚拟 DOM 节点 (vnode)。

类型

// 完整参数签名
function h(
  type: string | Component, //可以创建原生dom,也可以创建组件
  props?: object | null, // 可以给组件(原生dom)插入文字,添加事件等
  children?: Children | Slot | Slots
): VNode;

// 省略 props
function h(type: string | Component, children?: Children | Slot): VNode;

type Children = string | number | boolean | VNode | null | Children[];

type Slot = () => Children;

type Slots = { [name: string]: Slot };

渲染原生dom

const box = document.createElement('div');
const container = document.querySelector('#test');
container.appendChild(box);
box.innerHTML = `<h3>渲染原生dom</h3>`;
render(
  h('div', {
    innerHTML: 'h函数666',
    style: {
      color: 'red',
    },
    class: 'test',
  }),
  box
);

渲染组件

const box = document.createElement('div');
const container = document.querySelector('#test');
container.appendChild(box);
box.innerHTML = `<h3>渲染ant的按钮组件</h3>`;

render(
  h(AButton, {
    innerHTML: '按钮',
    onClick: () => {
      alert('按钮点击了');
    },
  }),
  box
);

h 函数中的 v-model

const switchValue = ref(false);
const hVModel = () => {
  const box = document.createElement('div');
  const container = document.querySelector('#test');
  container.appendChild(box);
  box.innerHTML = `<h3>v-model</h3>`;
  render(
    h(ASwitch, {
      checked: switchValue,
      ['onUpdate:checked']: (checked) => {
        switchValue.value = checked;
      },
    }),
    box
  );
};

使用场景(ant design 表格自定义渲染为例)

const columns: TableColumnsType = [
  {
    title: 'Name',
    dataIndex: 'name',
  },
  // ...
  {
    title: 'Tag',
    dataIndex: 'tag',
    customRender: ({ record }) => {
      const score = record['score'];
      if (score >= 90) {
        return h(ATag, { innerText: '优', color: '#108EE9' });
      } else if (score >= 80 && score < 90) {
        return h(ATag, { innerText: '良', color: '#2DB7F5' });
      } else if (score < 80 && score >= 60) {
        return h(ATag, { innerText: '中', color: '#87D068' });
      } else {
        return h(ATag, { innerText: '差', color: '#FF5500' });
      }
    },
  },
];

效果预览可访问https://guanghuijs.gitee.io/ghui-docs/blogs/h函数.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值