JSX语法、函数式组件
1.v-if、v-for
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.')
}
}
2. 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)
}
}
})
}
3. createElement的参数
// @returns {VNode}
createElement(
'div', // 一个 HTML 标签名、组件选项对象,或者一个 async 函数【必填】
{ // 一个与模板中 attribute 对应的数据对象【选填】
'class': {
foo: true,
bar: false
},
props: {
myProp: 'bar'
}
},
[ // 子级虚拟节点 (VNodes),由 `createElement()` 构建而成
'先写一些文字',
createElement('h1', '一则头条'),
createElement(
MyComponent,
{
props: {
someProp: 'foobar'
}
}
)
]
)
4. 插槽
你可以通过 this.$slots
访问静态插槽的内容,每个插槽都是一个 VNode 数组:
render: function (createElement) {
// `<div><slot></slot></div>`
return createElement('div', this.$slots.default)
}
也可以通过 this.$scopedSlots
访问作用域插槽,每个作用域插槽都是一个返回若干 VNode 的函数:
props: ['message'],
render: function (createElement) {
// `<div><slot :text="message"></slot></div>`
return createElement('div', [
this.$scopedSlots.default({
text: this.message
})
])
}
如果要用渲染函数向子组件中传递作用域插槽,可以利用 VNode 数据对象中的 scopedSlots
字段:
render: function (createElement) {
// `<div><child v-slot="props"><span>{{ props.text }}</span></child></div>`
return createElement('div', [
createElement('child', {
// 在数据对象中传递 `scopedSlots`
// 格式为 { name: props => VNode | Array<VNode> }
scopedSlots: {
default: function (props) {
return createElement('span', props.text)
}
}
})
])
}
5. 函数式组件(示例)
<script>
export default {
name: 'TextNotice',
functional: true,
props: {
showBackground: { // 是否显示文字背景
type: Boolean,
default: false
}
},
render: function (h, context) {
return (
<div class={['content__wrapper', {'show-background': context.props.showBackground}]}>
<div class="notice-content">
<div class="hint">
<i />
<span class="blue">提示:</span>
<span class="normal">{context.children}</span>
</div>
</div>
</div>
)
}
}
</script>