Vue 插槽 slot
Vue 使用slot插槽
11. 需求:
1. 父组件调用子组件并展示数据
2. 父组件调用多个子组件每个组件内显示的内容不同
3. 父组件调用子组件展示的数据和子组件展示的内容相同样式不同
1.2 子组件: 具名插槽,就是给插槽指定名称,然后 一 一对应
(1) 引入组件的页面,如果是多个内容,需要用template 包裹起来,并且添加 slot 属性和 自定义值 。
(2) slot 的值 需要和 组件中 <slot name='xxx'></slot> name的值相对应。
<template> <div class="container"> <h2>我是slotChild子页面</h2> <!-- 多个slot 场景:一个头部导航部分每个页面显示内容不同就需要多个插槽 --> <slot name="left"></slot> <slot name="center"></slot> <slot name="right"></slot> </div> </template> <script> export default { name:'slotChild', data(){ return{ qLanguage:['Java','C#','VUE'] } } } </script> <style scoped> .container{ width:100%; text-align: center; } </style>
父组件
<template> <div> <slotChild> <button slot="left">按钮1</button>
<template slot="center">
<button slot="center">按钮2</button>
</template>
// 显示一条不需要用templete
<button slot="right">按钮3</button>
</slotChild> // 此时这个组件就不会显示数据因为插槽需要name <!--<slotChild> <h3>说明文字</h3> </slotChild>--> </div> </template> <script> import slotChild from '../components/slotChild.vue' export default { name:'slotDemo', components:{ slotChild }, data(){ return{ } } } </script>
1.3 slot-scope 作用域插槽。
(1) 作用域插槽主要是 使用子组件的任何数据 来达到自定义显示内容的目的
(2) 作用域插槽最最最最最重要的一步,即是在<slot></slot> 上绑定数据 ,如果没有绑定数据,则父组件收到的,只是一个空对象{ }。
子组件
<template> <div class="container"> <h2>我是slotChild子页面</h2>
<slot>
<ul>
<li v-for="(item,index) in qLanguage" :key="index">{{ item }}</li>
</ul>
</slot>
</div> </template> <script> export default { name:'slotChild', data(){ return{ qLanguage:['Java','C#','VUE'] } } } </script> <style scoped> .container{ width:100%; text-align: center; } </style>
父组件
<template> <div> <slotChild> // slot-scope="自定义名称" <template slot-scope="slot"> // 自定义名称.子组件的name值 <span>{{slot.data}}</span> </template> </slotChild> </div> </template> <script> import slotChild from '../components/slotChild.vue' export default { name:'slotDemo', components:{ slotChild }, data(){ return{ } } } </script>