vue 作用域插槽的使用
<div id="app">
<cpn></cpn>
<cpn>
<!-- 2.获取子组件中的 pLanguage -->
<template slot-scope="slot">
<!-- <span v-for="item in slot.data">{{item}} -- </span> -->
<span>{{slot.data.join(' - ')}}</span>
</template>
</cpn>
<cpn>
<template slot-scope="slot">
<!-- <span v-for="item in slot.data">{{item}} **</span> -->
<span>{{slot.data.join(' * ')}}</span>
</template>
</cpn>
</div>
<template id="cpn">
<div>
<!-- 1.绑定 子传父-->
<slot :data="pLanguage">
<ul>
<li v-for ="item in pLanguage">{{item}}</li>
</ul>
</slot>
</div>
</template>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: "#app",
data: {
message: "你好",
isShow:true
},
methods: {},
components: {
cpn: {
template: "#cpn",
data(){
return{
pLanguage:['JavaScript','C++','C#','Python']
}
}
},
},
});
</script>
说明:
1.定义子组件 并在子组件中初始化数据 (pLanguage)
2.在子组件的插槽中 绑定 pLanguage (:data=“pLanguage” )其中的data可以随便取名
3.v-for循环遍历pLanguage
4.在父组件中使用子组件 cpn (通过template模板的 slot-scope=“slot” 获取子组件的pLanguage )
<!-- 2.获取子组件中的 pLanguage -->
<template slot-scope="slot">
<!-- <span v-for="item in slot.data">{{item}} -- </span> -->
<span>{{slot.data.join(' - ')}}</span>
</template>
5.通过 slot.data 获取到pLanguage的数据 (data是子组件插槽绑定的那个属性)
6.通过join进行分割处理 获取的data数据
<span>{{slot.data.join(' - ')}}</span>