详解详解Vue 匿名、具名和作用域插槽的使用方法匿名、具名和作用域插槽的使用方法
Vue 中的插槽在开发组件的过程中其实是非常重要并且好用的。Vue 的插槽也没有说很难使用,这篇文章简明扼要的介绍了三
种插槽的用法。
匿名插槽匿名插槽
子组件定义 slot 插槽,但并未具名,因此也可以说是默认插槽。只要在父元素中插入的内容,默认加入到这个插槽中去。
<template>
<div>
hello <slot>陌生人</slot>
</div>
</template>
这里定义了一个默认插槽,只要往里头丢东西,就会被加入到这个插槽里面
slot 元素里面可以加入一系列后备内容,一旦父元素没有插入任何信息,那么就会渲染后备内容。
<my-comp>
oli
</my-comp>
如在父组件中使用这个子组件,并插入 oli 字符串,效果如下:
具名插槽具名插槽
具名插槽可以出现在不同的地方,不限制出现的次数。只要匹配了 name 那么这些内容就会被插入到这个 name 的插槽中去。
<template>
<div>
<slot name="nav"></slot>
<br/>
<slot name="content"></slot>
<br/>
<slot name="footer"></slot>
</div>
</template>
比如上述代码定义了三个具名插槽。在父组件中即可使用 slot 属性插入到对应的插槽中:
<template>
<div>
<my-comp>
<template slot="nav">navigator</template>
<template slot="footer">footer</template>
<template slot="content">content</template>
</my-comp>
</div>
</template>
另外,顺序并不重要,content 在 footer 下方但依然能够按照 slot 定义的顺序渲染:
作用域插槽作用域插槽
通常情况下普通的插槽是父组件使用插槽过程中传入东西决定了插槽的内容。但有时我们需要获取到子组件提供的一些数据,
评论0