Vue 插槽 slot
Vue 使用slot插槽
11. 需求:
1. 父组件调用子组件并展示数据
2. 父组件调用多个子组件每个组件内显示的内容不同
3. 父组件调用子组件展示的数据和子组件展示的内容相同样式不同
1.2 子组件: 具名插槽,就是给插槽指定名称,然后 一 一对应
(1) 引入组件的页面,如果是多个内容,需要用template 包裹起来,并且添加 slot 属性和 自定义值 。
(2) slot 的值 需要和 组件中
<template> <div class="container"> <h2>我是slotChild子页面h2> <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">按钮1button>
// 显示一条不需要用templete
<button slot="right">按钮3button>
slotChild> // 此时这个组件就不会显示数据因为插槽需要name div> template> <script> import slotChild from '../components/slotChild.vue' export default { name:'slotDemo', components:{ slotChild }, data(){ return{ } } } script>
1.3 slot-scope 作用域插槽。
(1) 作用域插槽主要是 使用子组件的任何数据 来达到自定义显示内容的目的
(2) 作用域插槽最最最最最重要的一步,即是在
子组件
<template> <div class="container"> <h2>我是slotChild子页面h2>
- {{ item }}
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>