写一个关于插槽slot的文章记录一下
首先理解 编译作用域:父级模板的所有内容都是在父级作用域里边编辑的,子模板里的所有内容都是在子作用域里面编译的.
什么是插槽?
插槽就是子组件中用<slot></slot>给一个占位符,父组件在使用子组件的时候可以在这个占位符中填充任何代码
为什么使用插槽
加强组件的复用性,降低组件的耦合性,封装公共组件的时候预留插槽,使用者在使用的时候可以根据自己的需求,决定插槽内的内容.
插槽分为默认插槽,具名插槽,作用域插槽
默认插槽
默认插槽,默认把代码全部填充进去
子组件
<template>
<div>
<h5>你的名字是</h5>
<slot></slot>
</div>
</template>
<script>
export default {
name:'child',
data () {
return
}
}
</script>
父组件
<template>
<div>使用插槽:</div>
<div>
<child>
<span>卡尔</span>
</child>
</div>
</template>
<script>
import child form './child'
export default {
name:'father',
components:{child},
data () {
return
}
}
</script>
具名插槽
就是给插槽一个name属性,父组件在使用的时候使用插槽的name属性
子组件
<template>
<div>
<h5>我是标题</h5>
<slot name='title'></slot>
</div>
<div>
<h5>我是中间</h5>
<slot name='main'></slot>
</div>
<div>
<h5>我是底部</h5>
<slot name='footer'></slot>
</div>
</template>
<script>
export default {
name:'child',
data () {
return
}
}
</script>
父组件
<template>
<div>使用插槽:</div>
<div>
<child>
<template slot="title">
<span>使用slot</span>
</template>
<template slot="mian">
<span>我是中间的具体内容</span>
</template>
<template slot="footer">
<span>我是底部的具体内容</span>
</template>
</child>
</div>
</template>
<script>
import child form './child'
export default {
name:'father',
components:{child},
data () {
return
}
}
</script>
作用域插槽
父组件使用slot-scope属性来结构子组件,操作子组件的值
子组件
<template>
<div>
我是作用域插槽
<slot :data="user"></slot>
</div>
</template>
<script>
export default {
name: 'child',
data () {
return {
user: [
{name: '王大锤'},
{name: '铁锤'},
{name: '翠花'}
]
}
}
}
</script>
父组件
<template>
<div>使用插槽:</div>
<div>
<child>
<template slot-scope="user">
<div v-for="(item, index) in user.data" :key="index">
{{item}}
</child>
</div>
</template>
<script>
import child form './child'
export default {
name:'father',
components:{child},
data () {
return
}
}
</script>