Vue 2.x 渲染函数
createElement 参数
// returns {VNode}
createElement(params1, params2, params3)
params1
String | Object | Function
: 一个 HTML 标签名 | 组件选项对象 | 或者 resolve 了上述任何一种的一个 async 函数。 必填项
params2
Object
: 模板中 attribute 对应的数据对象。 可选
{
// 与 `v-bind:class` 的 API 相同,
// 接受一个字符串、对象或字符串和对象组成的数组
'class': {
foo: true,
bar: false
},
// 与 `v-bind:style` 的 API 相同,
// 接受一个字符串、对象,或对象组成的数组
style: {
color: 'red',
fontSize: '14px'
},
// HTML 特性
attrs: {
id: 'foo'
},
// 组件 prop
props: {
myProp: 'bar'
},
// dom 属性
domProps: {
innerHTML: 'baz'
},
// 事件监听器在 `on` 内,
// 但不再支持如 `v-on:keyup.enter` 这样的修饰器。
// 需要在处理函数中手动检查 keyCode。
on: {
click: this.clickHandler
},
// 仅用于组件,用于监听原生事件,而不是组件内部使用
// `vm.$emit` 触发的事件。
nativeOn: {
click: this.nativeClickHandler
},
// 自定义指令。注意,你无法对 `binding` 中的 `oldValue`
// 赋值,因为 Vue 已经自动为你进行了同步。
directives: [
{
name: 'my-custom-directive',
value: '2',
expression: '1 + 1',
arg: 'foo',
modifiers: {
bar: true
}
}
],
// 作用域插槽的格式为
// { name: props => VNode | Array<VNode> }
scopedSlots: {
default: props => createElement('span', props.text)
},
// 如果组件是其它组件的子组件,需为插槽指定名称
slot: 'name-of-slot',
// 其它特殊顶层 property
key: 'myKey',
ref: 'myRef',
// 如果你在渲染函数中给多个元素都应用了相同的 ref 名,
// 那么 `$refs.myRef` 会变成一个数组。
refInFor: true
}
params3
Array | String
: 子级虚拟节点 (VNodes array),由 createElement()
构建而成 | 也可以使用字符串来生成 文本虚拟节点。 可选
使用 JavaScript 代替模板功能
v-if 和 v-for
<ul v-if="items.length">
<li v-for="item in items">{{ item.name }}</li>
</ul>
<p v-else>No items found.</p>
props: ['items'],
render: function (createElement) {
if (this.items.length) {
return createElement('ul', this.items.map(function (item) {
return createElement('li', item.name)
}))
} else {
return createElement('p', 'No items found.')
}
}
v-model
props: ['value'],
render: function (createElement) {
var self = this
return createElement('input', {
domProps: {
value: self.value
},
on: {
input: function (event) {
self.$emit('input', event.target.value)
}
}
})
}
事件 & 按键修饰符
插槽相关
this.$slots
编写静态插槽,返回 VNode 数组
render: function (createElement) {
return createElement('div', this.$slots.default)
// 或者 return createElement('div', this.$scopedSlots.default())
}
// `<div><slot></slot></div>`
this.$scopedSlots
编写作用域插槽,每个作用域插槽都是一个返回若干 VNode array 的函数
props: ['message'],
render: function (createElement) {
return createElement('div', [
this.$scopedSlots.default({
text: this.message
})
])
}
// `<div><slot :text="message"></slot></div>`
scopedSlots
编写作用域插槽 属性
render: function (createElement) {
return createElement('div', [
createElement('child', {
// 在数据对象中传递 `scopedSlots`
// 格式为 { name: props => VNode | Array<VNode> }
scopedSlots: {
default: function (props) {
return createElement('span', props.text)
}
}
})
])
}
// `<div><child v-slot="props"><span>{{ props.text }}</span></child></div>`
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

上一篇: Vue 2.x 插槽
下一篇: TypeScript 常见问题
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论