vue关于slot、render的用法
通过下面一段代码展示
<script src="https://unpkg.com/marked@0.3.6"></script>
<script src="https://unpkg.com/lodash@4.16.0"></script>
<div id="editor">
<page>
<right slot="right"></right>
<left slot="left"></left>
<span>哈哈</span>
<span>Hello</span>
</page>
<heading :level="1">i'm header</heading>
</div>
var vm = ''
var leftContext = ''
const left = {
template: '<span>{{name}}</span>',
data () {
return {
name: 'left'
}
}
}
const right = {
template: '<span>right</span>'
}
const page = {
template: `<div :style="{height: height}">
<slot name="left"></slot>
<span>间隔</span>
<slot name="right"></slot>
<slot></slot>
</div>`,
mounted () {
console.log('\npage:')
console.log('this.$slots: ', this.$slots)
console.log('this.$slots.default: ', this.$slots.default)
leftContext = this.$slots.left[0].context
},
data () {
return {
height: '50px'
}
}
}
const heading = {
render (h) {
return h('h' + this.$props.level, this.$slots.default)
},
mounted () {
console.log('\nheading:')
console.log('this.$slots: ', this.$slots)
console.log('this.$slots.default: ', this.$slots.default)
},
props: {
level: {
type: Number,
required: true
}
}
}
new Vue({
el: '#editor',
components: {
'left': left,
'right': right,
'page': page,
'heading': heading
},
mounted () {
vm = this
console.log('\n\n\nleftContext', leftContext)
console.log('\nvm: ', vm)
console.log('\n leftContext.$options === vm.$options: ', leftContext.$options === vm.$options)
}
})
slot
a. 具名slot使用:在组件中通过<slot name="left"></slot>
定义一个具名的插槽,在使用组件的时候通过<left slot="left"></left>
即可将代码插入插槽中
b. 未命名的slot属于默认插槽,组件包含的内容(具名插槽除外)将插入默认插槽中render: 使用方法类似react的render
每个返回的slot都是一个VNode,VNode的context就是new Vue(……)返回的对象