<template>
<ParentCmp />
</template>
<script>
import ParentCmp from './ParentCmp';
export default {
components: {
ParentCmp
},
}
</script>
![](https://img.haomeiwen.com/i15197612/3530521a2209c4d1.png)
image.png
- ParentCmp.vue (template写法)
<template>
<div>
<h1>我是parent组件</h1>
<hr />
<User style="background: #ccc" text="我是传入的文本">
<template v-slot:header>
<p>这是名字为header的slot</p>
</template>
<p>这是填充默认slot数据</p>
<template v-slot:footer>
<p>这是名字为footer的slot</p>
</template>
<template v-slot:item="props">
<p>名字为item的作用域插槽。显示数据{{props}}</p>
</template>
<template v-slot:list="props">
<p>名字为list的作用域插槽。显示数据{{props}}</p>
</template>
</User>
</div>
</template>
<script>
import User from './User'
export default {
components: {
User
},
props: {},
data() {
return {}
},
methods: {}
}
</script>
<template>
<div>
<h4>{{text}}</h4>
<slot name="header"></slot>
<slot>默认的user slot</slot>
<slot name="footer"></slot>
<slot name="item" v-bind="item">item作用域插槽,展示姓名 {{item.name}}</slot>
<slot name="list" v-bind="{list}">list作用域插槽</slot>
</div>
</template>
<script>
export default {
props: {
text: String
},
data() {
return {
item: {
name: '张三',
age: 28,
works: '前端、后端、设计、产品'
},
list: ['a','b','c']
}
}
}
</script>
import User from './User'
export default {
props: {},
data() {
return {}
},
methods: {},
render(h) {
return h('div',[
h('h1', '我是parent组件'),
h('hr'),
h(User, {
props: {
text: '我是传入的文本'
},
style: {
background: '#ccc'
},
// 作用域插槽写在scopedSlots里
scopedSlots: {
item: props => h('p', `名字为item的作用域插槽。显示数据${JSON.stringify(props)}`),
list: props => h('p', `名字为list的作用域插槽。显示数据${JSON.stringify(props)}`)
}
},
// 非作用域插槽写数组里
[
h('p', {slot: 'header'}, '这是名字为header的slot'),
h('p', '这是填充默认slot数据'),
h('p', {slot: 'footer'}, '这是名字为footer的slot'),
])
]);
// jxs写法
/* return (
<div>
<h1>我是parent组件</h1>
<hr />
<User
style="background: #ccc"
text="我是传入的文本"
scopedSlots={
{
item: props => (<p>名字为item的作用域插槽。显示数据{JSON.stringify(props)}</p>),
list: props => (<p>名字为list的作用域插槽。显示数据{JSON.stringify(props)}</p>),
}
}
>
<p slot="header">这是名字为header的slot</p>
<p>这是填充默认slot数据</p>
<p slot="footer">这是名字为footer的slot</p>
</User>
</div>
); */
}
}
export default {
props: {
text: String
},
data () {
return {
item: {
name: '张三',
age: 28,
works: '前端、后端、设计、产品'
},
list: ['a', 'b', 'c']
}
},
methods: {
getSlot (name, data) {
if (this.$scopedSlots[name]) {
return this.$scopedSlots[name](data);
} else if (this.$slots[name]) {
return this.$slots[name];
}
return undefined;
},
},
render (h) {
return h('div', [
h('h4', this.text),
this.getSlot('header'),
this.$slots.default,
this.getSlot('footer'),
this.getSlot('item', this.item),
this.getSlot('list', {list: this.list}),
])
// jxs写法
/* return (
<div>
<h4>{this.text}</h4>
{this.getSlot('header')}
{this.$slots.default}
{this.getSlot('footer')}
{this.getSlot('item', this.item)}
{this.getSlot('list', {list: this.list})}
</div>
); */
}
}
网友评论