[ 前端框架/Vue ] render函数
render函数
实例
html
<div id="app">
<anchored-heading :level="1" v-slot:myslot>Hello world!</anchored-heading>
</div>
javascript
var getChildrenTextContent = function (children) {
// 取得模板中的文本值,即 `Hello world!`
return children.map(function (node) {
return node.children
? getChildrenTextContent(node.children)
: node.text
}).join('')
}
// 注册全局组件
Vue.component('anchored-heading', {
// render start
render: function (createElement) {
// 创建 kebab-case 风格的 ID,得到 `hello-world`
var headingId = getChildrenTextContent(this.$slots.myslot)
.toLowerCase()
.replace(/\W+/g, '-')
.replace(/(^-|-$)/g, '')
return createElement(
// Element name
'h' + this.level,
// [] 里包含子元素
[
// 另一个元素
createElement(
'a',
// 元素的属性值
{
attrs: {
name: headingId,
href: '#' + headingId
}
},
// 子元素
[
// 值为 this.$slot.myslot 绑定到祖父组件的值
createElement('span', this.$slots.myslot)
])
]
)
}, //render end
props: {
level: {
type: Number,
required: true
}
}
})
new Vue({
el: '#app',
data: {
}
官方文档
createElement函数
下面是createElement函数接收的参数
javascript
// @returns {VNode}
createElement(
// {String | Object | Function}
// 一个 HTML 标签名、组件选项对象,或者
// resolve 了上述任何一种的一个 async 函数。必填项。
'div',
// {Object}
// 一个与模板中 attribute 对应的数据对象。可选。
{
// 见下一个代码块
},
// {String | Array}
// 子级虚拟节点 (VNodes),由 `createElement()` 构建而成,
// 也可以使用字符串来生成“文本虚拟节点”。可选。
[
'先写一些文字',
createElement('h1', '一则头条'),
createElement(MyComponent, {
props: {
someProp: 'foobar'
}
})
]
)
一个与模板中 attribute 对应的数据对象
javascript
{
// 与 `v-bind:class` 的 API 相同,
// 接受一个字符串、对象或字符串和对象组成的数组
'class': {
foo: true,
bar: false
},
// 与 `v-bind:style` 的 API 相同,
// 接受一个字符串、对象,或对象组成的数组
style: {
color: 'red',
fontSize: '14px'
},
// 普通的 HTML attribute
attrs: {
id: 'foo'
},
// 组件 prop
props: {
myProp: 'bar'
},
// DOM property
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
}
博主水平有限,难免疏漏有误,欢迎交流指正。
博客为作者原创,版权所有,保留一切权利。仅供学习和参考,转载必须注明博主ID和转载链接。
博客为作者原创,版权所有,保留一切权利。仅供学习和参考,转载必须注明博主ID和转载链接。