插槽:预留的位置,父组件在使用时在组件标签中间写的内容,会填充到slot的位置
即使用组件时,可以往插槽中传递内容
直接写在组件中的内容,会填充到默认的插槽中(没有用name属性起名字的插槽)
<template>
<div class="box1">
box1
<slot></slot>
</div>
</template>
<script>
export default{
data(){
return{
}
},
methods:{
}
}
</script>
<style>
.box1{
width: 100px;
height: 100px;
background:darkcyan;
}
</style>
<template>
<slot1>
<h2>studing</h2>
</slot1>
</template>
<script>
import slot1 from './components/Slot1.vue'
export default {
data(){
return{
}
},
methods:{
del(index){
this.stu1.splice(index,1)
}
},
name: 'App',
components: {
slot1
}
};
</script>
<style>
</style>
父组件中通过这种形式去子组件中填充内容(固定的)
working
working
可以简写成
working
<template>
<div class="box1">
box1
<slot></slot>
</div>
<div class="box2">
box2
<slot name="s1"></slot>
</div>
<div class="box3">
box3
<slot name="s2"></slot>
</div>
</template>
<script>
export default{
data(){
return{
}
},
methods:{
}
}
</script>
<style>
.box1{
width: 100px;
height: 100px;
background:darkcyan;
float: left;
}
.box2{
width: 100px;
height: 100px;
background:gold;
float: left;
}
.box3{
width: 100px;
height: 100px;
background:burlywood;
float: left;
}
</style>
<template>
<slot1>
<!-- 1、直接写在组件中的内容,会填充到默认插槽中 -->
<h2>studing</h2>
<template v-slot:s1><h2>working</h2></template>
<template v-slot:s2><h2>playing</h2></template>
</slot1>
</template>
<script>
import slot1 from './components/Slot1.vue'
export default {
data(){
return{
}
},
methods:{
del(index){
this.stu1.splice(index,1)
}
},
name: 'App',
components: {
slot1
}
};
</script>
<style>
</style>
在组件中定义插槽的时候,给插槽中预留位置用在接收data中的传过来的数据;
其他组件在使用这个组件的时候,可以获得该传递过来的数据
简单总结:
定义插槽的时候,把一些数据传出去(例如:item="info")就是把这些数据绑定到插槽上面;
当用到这个插槽的时候,在插槽后面用个="变量",去接收;变量通常使用scope
除了name属性,其他的属性都会被打包成一个对象,传递给变量;
Slot.vue
<template>
<div class="box4">
box4
<slot></slot>
</div>
<div class="box5">
box5
<slot name="s1" :item="info"></slot>
</div>
<div class="box6">
box6
<slot name="s2"></slot>
</div>
</template>
<script>
export default{
data(){
return{
info:{id:1,
name:'zs',
age:18,
},
}
}
}
</script>
<style>
.box1{
width: 200px;
height: 200px;
background:darkcyan;
float: left;
}
.box2{
width: 200px;
height: 200px;
background:gold;
float: left;
}
.box3{
width: 200px;
height: 200px;
background:burlywood;
float: left;
}
</style>
App.vue
<template>
<slot2>
<!-- <template #s1='scope'> -->
<template v-slot:s1='scope'>
<h3>信息:{{scope}}</h3>
<h3>姓名:{{scope.item.name}}</h3>
</template>
</slot2>
</template>
<script>
import slot2 from './components/Slot2.vue';
export default {
data(){
return{
stu1:[
{id:1,name:'zs',age:18},
{id:2,name:'lisi',age:19},
{id:3,name:'ww',age:17}
],
stu2:[
{id:1,name:'zs',age:18},
{id:2,name:'lisi',age:19},
{id:3,name:'ww',age:17}
],
}
},
methods:{
del(index){
this.stu1.splice(index,1)
}
},
name: 'App',
components: {
slot2
}
};
</script>
<style>
</style>