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()
)
}