`基础用法 单个(匿名)插槽`//父组件<template><div><!--下面这种形式叫插槽(双标签形式)--><ChildA>你好</ChildA><ChildA><input type="text"></ChildA><ChildA></ChildA></div></template><script>import ChildA from"@/components/slotsView/ChildA.vue"exportdefault{name:"SlotsView",components:{
ChildA
}}</script>//子组件<template><div>
a
<slot>默认值</slot>
b
</div></template><script>exportdefault{name:"childA"}</script>
案例 使用插槽渲染表格
`插槽内容可以访问到父组件的数据作用域,因为插槽内容本身是在父组件模板中定义的,插槽内容无法访问子组件的数据``父组件模板中的表达式只能访问父组件的作用域;子组件模板中的表达式只能访问子组件的作用域`//父组件<template><div><ChildB><!--
list 是一个数组 item是每一项值是对象类型
index是对应值的下标
key是item中对应属性名 value是key对应的属性值
--><tr v-for="(item, index) in list":key="index"><td v-for="(value, key) in item":key="key">{{ value }}</td></tr></ChildB></div></template><script>import ChildB from"@/components/slotsView/ChildB.vue"exportdefault{name:"SlotsView",components:{
ChildB
},data(){return{list:[{name:"张三",age:30,sex:"男",tel:"18617263823",img:"/img/3.jpg"},{name:"李四",age:21,sex:"女",tel:"18617342823",img:"/img/4.jpg"},{name:"王五",age:23,sex:"男",tel:"18617262345",img:"/img/5.jpg"},{name:"赵六",age:24,sex:"女",tel:"18612452823",img:"/img/6.jpg"},]}}}</script>//子组件<template><table><thead><tr><th>name</th><th>sex</th><th>age</th><th>tel</th></tr></thead><tbody>//slot 获取到父组件值传递的内容<slot></slot></tbody></table></template><script>exportdefault{name:"childB"}</script><style>
table {width: 1200px;
border-collapse: collapse;}
th,
td {height: 30px;
line-height: 30px;
text-align: center;border: 1px solid #000;}</style>
具名插槽
//如果当前有一个以上的插槽,我们就需要给每个插槽具名,设置name//父组件<template><div><!-- 会自动放入默认的插槽中 --><!--<ChildC>abcde</ChildC>--><ChildC>//通过设置的name 把内容放到对应的slot中<template #header><input type="text"></template><template #footer><button>按钮</button></template></ChildC></div></template><script>import ChildC from"@/components/slotsView/ChildC.vue"exportdefault{name:"SlotsView",components:{
ChildC
},data(){return{}}}</script>//子组件<template><div>
a
<slot name="header"></slot>
b
</div><hr /><div>
a
<slot name="footer"></slot>
b
</div><p>//我们如果希望其中有一个是默认插槽,正常给组件标签填入的内容,就会自动放入这个默认的插槽中 默认插槽名必须起名为defalut<slot name="default"></slot></p></template><script>exportdefault{name:"ChildC"}</script>
条件插槽
//根据插槽是否存在来渲染某些内容,结合使用 $slots 属性与 v-if 来实现<template><Card><template #header><h1>This is the header</h1></template><template #default><p>This is the content</p></template><template #footer><em>This is the footer</em></template></Card></template><template><div class="card">// 若$slots.header 为真就把内容放到下面的插槽中<div v-if="$slots.header"class="card-header"><slot name="header"/></div><div v-if="$slots.default"class="card-content"><slot /></div><div v-if="$slots.footer"class="card-footer"><slot name="footer"/></div></div></template>