vue的渲染函数
为什么用
- 组件模版逻辑性比较复杂的时候需要用到
- 多一种组件定义的选择
- 对模版的控制力更强
- 书写方式对react开发同学比较友好
是什么
用脚本动态的创建组件模版的一种方式,使用createElement方法创建一个VNode。
const CustomComponent = Vue.component({
render(createElement) {
return createElement(
String:tag-name | Object:component-option,
{
...data-option
},
Array<String | VNode>
)
})
})
data-option
{
text-color: true,
margin-10: false
}
即:
<custom-component class="text-color"></custom-component>
即:
<custom-component id="bar"></custom-component>
在组件中通过this.$attrs可以获取。
- props: {name: any}
组件内部的props,需要通过组件定义选项中的props来申明才能在组件内部使用。例如:
const Button = {
props: ['text'],
template: '<button type="button">{{text}}</button>',
created() {
console.log(this.url) //undefined
}
};
const LinkButton = {
render(createElement) {
return createElement(
Button,
{
props: {
text: 'bar',
url: 'https://mi.com'
},
on: {
navigate() {}
}
}
);
}
}
-
domProps: {name: any}
DOM的属性,例如innerHTML,如果设置了innerHTML,则子组件就不生效了。
-
on: {name: function}
也就是template上面的v-on,通过$emit触发
-
nativeOn: {name: function}
对于原生的dom标签不起作用,只作用于组件,与$emit触发的事件区别开来。
-
directives: Array
模版上的自定义指令
-
scopedSlots: {name: props => VNode}
配置作用域插槽,例如:
const NumColumn = {
functional: true,
render(createElement, context) {
return createElement(TableColumn, {
props: context.props,
scopedSlots: {
default(scope) {
return createElement(
'div',
{},
[thousands(scope.row[context.props.prop])]
);
}
}
});
}
};
- slot: string
- key: string
- ref: string
- refInFor: boolean
props和attrs的区别
渲染函数的attrs会显示在组件的跟节点上,模版上的attrs不一定会显示在跟节点上,取决于组件定义中的inheriteAttrs的值是否为true.
props是在组件内部使用的特性,需要通过props选项来做申明。
on和nativeOn的区别
on就等同于模版中的v-on,对于html标签元素,只有on,对于组件,on是$emit触发的监听函数,nativeOn是针对组件中所有原生事件的监听函数。例如:
const PrefixInput = {
props: ['prefix'],
render(createElement) {
return createElement('div', [this.prefix, createElement(
'input',
{
attrs: {
type: 'text'
},
}
)])
}
};
const Search = {
render(createElement) {
const that = this;
return createElement('label', ['搜索:', createElement(PrefixInput, {
prefix: SearchIcon,
nativeOn: {
change(evt) {
console.log(evt.target.value) //这里可以获取input输入框的值
that.$emit('searh', evt.target.value);
}
}
})])
}
}
示例

vue的渲染函数
为什么用
是什么
用脚本动态的创建组件模版的一种方式,使用createElement方法创建一个VNode。
data-option
即:
style: {property: string}
attrs: {name: any}
即:
在组件中通过
this.$attrs可以获取。组件内部的props,需要通过组件定义选项中的props来申明才能在组件内部使用。例如:
domProps: {name: any}
DOM的属性,例如innerHTML,如果设置了innerHTML,则子组件就不生效了。
on: {name: function}
也就是template上面的v-on,通过$emit触发
nativeOn: {name: function}
对于原生的dom标签不起作用,只作用于组件,与$emit触发的事件区别开来。
directives: Array
模版上的自定义指令
scopedSlots: {name: props => VNode}
配置作用域插槽,例如:
props和attrs的区别
渲染函数的
attrs会显示在组件的跟节点上,模版上的attrs不一定会显示在跟节点上,取决于组件定义中的inheriteAttrs的值是否为true.props是在组件内部使用的特性,需要通过props选项来做申明。on和nativeOn的区别
on就等同于模版中的v-on,对于html标签元素,只有on,对于组件,on是$emit触发的监听函数,nativeOn是针对组件中所有原生事件的监听函数。例如:示例