父級組件
<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>
就會把相對應的新樣式結構加入到原來的組件之中,非常的方便與靈活