vue的函数组件(functional: true),它是无状态 (没有响应式数据),无实例 (没有 this 上下文),组件需要的一切都是通过上下文传递。可以通过对现有的组件,进行包装,返回一个新的组件。 当函数组件使用slot时,命名slot将会无效,所有的命名slot全部当做default slot。例如: ProgressBar组件: 。。。 this is progress1
<div class="progress-bg">
<div class="progress-value0" :style="{width: frameWidth + '%'}">
<div class="label-wrapper" v-if="frameWidth">
{{frameWidth}}
</div>
</div>
</div>
<slot name="second">
this is progress2
</slot>
。。。
Vue.component('Test-view',{
name:'Test-view',
functional: true,
props:{
name:{
type: String,
default: 'default'
}
},
render(createElement,ref){
let data = ref.data ||{};
const h = createElement;
data.props = {
game: 333,
salary: '5%',
value: 90,
bgColor:'red',
valueColor:'black'
};
data.style = {
background: 'white',
fontSize: '32px'
}
return h(ProgressBar,data,ref.children)
}
复制代码
})
使用TestView组件时:
this test-view
this test-second
ui最后展示的结果时: 插入的内容都被渲染在了default slot 中,命名slot second中没有值。因为vue中能够实现name-slot的分发,因此翻看vue-router的源代码发现解决办法。不要使用自己的createElement方法,要使用parent的createElement方法,
Vue.component('Test-view',{ name:'Test-view', functional: true,// 函数组件 render(_,content){ let {data,porps,children,slots} = content; let h = content.parent.$createElement; return h('组件名',data,children) } })