vue中插槽的使用总结
插槽概念:
插槽,也就是slot,是组件的一块HTML模板,这块模板显不显示,以及怎样显示,由父组件决定;
但是插槽显示的位置由子组件自身决定,slot写在组件template的哪块,父组件传过来的模板将来就显示在哪块。
简单的说,插槽就是可以让开发者自定义地往子组件中放置代码片段而开发出来的东西。就好像专门在某几个地方弄了几个槽(子组件中),我们开发时,就可以在对应的槽中放置对应的代码了。
分类
默认插槽(匿名插槽|单个插槽)
匿名插槽不需要设置name属性,一个组件里面只能有一个该类的插槽。相应的具名插槽一个组件里面就可以有多个,只要设置name属性就可以。
//父组件
<template>
<div>
<p>这里是父组件</p>
<child>
<p>我是插槽显示内容</p>
</child>
</div>
</template>
<script>
import Child from "../components/child";
export default {
name: "fatherSolt",
components: {
Child
}
};
</script>
//子组件
<template>
<div>
<p>这里是子组件</p>
<slot></slot>
</div>
</template>
效果图
如果子组件里面没有slot这个插槽,那么该组件起始标签到结束标签之间的所有内容都不会显示。
具名插槽
具名插槽是带name属性的。如果需要在组件内部预留多个插槽位置,就需要给插槽定义名字,然后插入到相应的位置。自vue2.6.0起有所更新,用v-slot代替slot和slot-scope。
在向具名插槽提供内容的时候,我们可以在一个< template>元素上使用 v-slot 指令,并以 v-slot 的参数的形式提供其名称
// 父组件
<template>
<div>
<p>这里是父组件</p>
<child>
<template v-slot:header>
<div>我是名字为header的具名插槽</div>
</template>
<template v-slot:main>
<div>我是名字为main的具名插槽</div>
</template>
<template v-slot:footer>
<div>我是名字为footer的具名插槽</div>
</template>
</child>
</div>
</template>
<script>
import Child from "../components/child";
export default {
name: "fatherSolt",
components: {
Child
}
};
</script>
// 子组件
<template>
<div>
<p>我是子组件</p>
<slot name="header"></slot>
<slot name="main"></slot>
<slot name="footer"></slot>
</div>
</template>
效果图
具名插槽的缩写
把参数之前所有的内容(v-slot:)换成#,注意如果要使用缩写的话,必须要有确定的参数名。
比如
<template #header>
<div>我是名字为header的具名插槽</div>
</template>
作用域插槽
作用域插槽,也叫作带数据的插槽,作用域插槽要求,要在solt上绑定数据。由于父级模板里的所有内容都是在父级作用域中编译的,子模板里的内容都是在子组件作用域中编译的,所以数据访问存在作用域问题,父组件不可以访问子组件的数据,为了让插槽内容能够访问子组件中才有的数据,将需要的特性绑定在插槽上——使用插槽prop。
//父组件
<template>
<div>
<p>这里是父组件</p>
<child>
<template v-slot = "msg">
<span v-for="(item,index) in msg.data" :key="index">{{item.week}}</span>
</template>
</child>
</div>
</template>
<script>
import Child from "../components/child";
export default {
name: "fatherSolt",
components: {
Child
}
};
</script>
//子组件
<template>
<div>
<p>我是子组件</p>
//作用域插槽,给子组件加上绑定内容
<slot :data="data"></slot>
</div>
</template>
<script>
export default {
data() {
return {
data: [
{ week: "星期一" },
{ week: "星期二" },
{ week: "星期三" },
{ week: "星期四" }
]
};
}
};
</script>
效果图