父级组件
<template>
<div class="wrapper">
<son1 title="标题3" :content="listData3" @father="teClick">
<template v-slot="scope">
<b class="qianz">{{scope.item.prefix ? '有前缀' : '无前缀'}}</b>
</template>
</son1>
</son1>
</div>
</template>
<script>
import son1 from './1_son.vue';
export default {
components: {
son1
},
props: {},
data() {
return {
listData1: ['列表项1', '列表项2', '列表项3'],
listData2: [{ text: '第二个列表的列表项1', img: 'example.png' }, { text: '第二个列表的列表项2', img: 'example.png' }, { text: '第二个列表的列表项3', img: 'example.png' }],
listData3: [
{ text: '第三个列表的列表项1', prefix: true, remark: '附加的备注1' },
{ text: '第三个列表的列表项2', prefix: false, remark: '附加的备注2' },
{ text: '第三个列表的列表项3', prefix: true, remark: '附加的备注3' }
],
list: [
{
name: 'tate',
age: 26,
single: true,
stu: false,
state: 1
},
{
name: 'kevin',
age: 23,
single: true,
stu: true,
state: 2
},
{
name: 'harden',
age: 28,
single: false,
stu: false,
state: 3
},
{
name: 'Jimmy',
age: 29,
single: false,
stu: true,
state: 4
}
]
};
},
watch: {},
computed: {},
methods: {
teClick(vl) {
console.log('我是', vl);
}
},
created() {},
mounted() {}
};
</script>
<style scoped>
.wrapper {
}
.qianz {
color: green;
}
</style>
子级组件
<template>
<div class="wrapper">
<div class="list">
<div class="list-title">{{title}}</div>
<ul class="list-content">
<li v-for="(item ,index) in content" :key="index">
<div class="texheader">
<div class="tximg"></div>
<div @click="listD(item.text)">{{item.text}}</div>
</div>
<slot :item="item">{{item}}</slot>
<div>我是页眉我是页眉我是页眉我是页眉我是页眉</div>
<!-- <slot :item="item">{{item}}</slot> -->
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
components: {},
props: {
content: {
type: Array
},
title: {
type: String,
required: true
}
},
data() {
return {};
},
watch: {},
computed: {},
methods: {
listD(data) {
this.$emit('father', data);
}
},
created() {},
mounted() {
console.log(this.content);
}
};
</script>
<style scoped>
.wrapper {
width: 600px;
}
.tximg {
width: 50px;
height: 50px;
background: green;
}
.texheader {
display: flex;
flex-direction: row;
align-items: center;
}
.list-content {
color: blue;
list-style: none;
display: flex;
flex-direction: row;
}
.list-content li {
width: 33.33%;
}
.list-title {
color: orange;
}
/* .list {
width: 200px;
height: 200px;
border: 1px solid #cacaca;
} */
</style>
总结:
最重要的展现是:
在子组件当中,有一条<slot :item="item">{{item}}</slot>,它的作用有2条:
1>把从父组件通过props传到子组件的值传到了父组件的
v-slot="scope" 通过scope.item就可以获取到相对应的数组对象
2>子组件其实已经有一定的结构了,当什么时候需求改变了,又需要在以前的组件中重新扩展一些内容的时候,这个时候就能体现出作用域插槽的作用了
子组件的<slot :item="item">{{item}}</slot>插在原来子组件位置的哪里;父组件通过
<template v-slot="scope">
<b class="qianz">{{scope.item.prefix ? '有前缀' : '无前缀'}}</b>
</template>
就会把相对应的新样式结构加入到原来的组件之中,非常的方便与灵活
