vue3_渲染函数

Vue 提供了一个 h() 函数用于创建 vnodes

h函数接收三个参数

  • type 元素类型
  • props 例如(style,class,innerHTML等)
  • children 子节点

h函数使用形式:

// 除了类型必填以外,其他的参数都是可选的
h('div')
h('div', { id: 'foo' })

// attribute 和 property 都能在 prop 中书写
// Vue 会自动将它们分配到正确的位置
h('div', { class: 'bar', innerHTML: 'hello' })

// 像 `.prop` 和 `.attr` 这样的的属性修饰符
// 可以分别通过 `.` 和 `^` 前缀来添加
h('div', { '.name': 'some-name', '^width': '100' })

// 类与样式可以像在模板中一样
// 用数组或对象的形式书写
h('div', { class: [foo, { bar }], style: { color: 'red' } })

// 事件监听器应以 onXxx 的形式书写
h('div', { onClick: () => {} })

// children 可以是一个字符串
h('div', { id: 'foo' }, 'hello')

// 没有 props 时可以省略不写
h('div', 'hello')
h('div', [h('span', 'hello')])

// children 数组可以同时包含 vnodes 与字符串
h('div', ['hello', h('span', 'hello')])

一些其他用法:

  • props传参
//模板中
 <btn text="编辑"></btn>
//函数中

const btn = (props:Props,ctx:any)=>{
    return h('button',
    {
        class:'shadow-lg bg-blue-500 text-white',
    },
    props.text
    )
}
  • emit派发
//模板中
<btn text="编辑" @gohome="go"></btn>

const btn = (props:Props,ctx:any)=>{
    return h('button',
    {
        class:'shadow-lg bg-blue-500 text-white',
        onClick:()=>{
          ctx.emit('gohome',123)  
        },
    },
    props.text
    )
}
const go = (num:number) =>{
    console.log(num);//123
}
  • 插槽
//模板中
<btn>
   <template #default>变了</template>
</btn>

//函数中
const btn = (props:Props,ctx:any)=>{
    return h('button',
    {
        class:'shadow-lg bg-blue-500 text-white',
    },
    ctx.slots.default()
    )
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值