文章灵感来源于vx文章,二更所以更简短,详情可参考Vue官网。
插槽solt
插槽:子组件提供给父组件使用的一个占位符<slot></slot>,给子组件本身开启一个插槽。父组件可以在这个占位符中填充任何模板代码,如HTML、组件等。填充的内容会替换子组件的<slot></slot>标签。
应用场景:已有组件不能满足复杂的需求,而通过slot来分发内容,使得组件具有更强的通用性。
插槽类型
-
匿名插槽,
<slot>元素没有 attribute:name,但是可以带有隐含的名字“default”。 -
具名插槽,
<slot>元素有一个特殊的 attribute:name。 -
作用域插槽,就是
在父组件中访问子组件的数据,或者从数据流向的角度来讲就是将子组件的数据传递到父组件。
旧插槽语法
<!-- 父组件 -->
<CRbutton>
<span>默认插槽 - 插入值</span>
<template #myName>具名插槽</template>
<template slot-scope="scope" slot="otherName">
{{ scope }}
</template>
</CRbutton>
<!-- 子组件 -->
<template>
<el-button type="primary">
<!-- 默认插槽 -->
<slot>默认插槽 - 默认值</slot>
<!-- 具名插槽 -->
<slot name="myName">具名插槽</slot>
<!-- 作用域插槽 + 具名插槽 -->
<slot :msg="msg" name="otherName"></slot>
</el-button>
</template>
新插槽语法
<!-- 父组件,与旧语法不同 -->
<CRbutton>
<span>默认插槽 - 插入值</span>
<template v-slot:myName>具名插槽</template>
<template #otherName="scope">
{{ scope }}
</template>
</CRbutton>
<!-- 子组件,同旧语法不变 -->
<template>
<el-button type="primary">
<!-- 默认插槽 -->
<slot>默认插槽 - 默认值</slot>
<!-- 具名插槽 -->
<slot name="myName">具名插槽</slot>
<!-- 作用域插槽 + 具名插槽 -->
<slot :msg="msg" name="otherName"></slot>
</el-button>
</template>
新旧语法的概述区别,可参考官网