具名插槽、作用域插槽的新写法
-
具名插槽
自 2.6.0 起有所更新。已废弃的使用
slotattribute 的语法但是我们有了新的语法,如下:
子组件 childCom:
<template id="childCom"> <div> <!-- 具名插槽的针对于组件中不止一个插槽的情况下使用,使用方式,即:给每个插槽指定 name 属性,在使用的时候需要给标签设置 slot 属性,且属性值为 对应的 name 属性的属性值 --> <slot name='left'><span>左边</span></slot> <!--给每个插槽命名,插槽中间是默认内容--> <slot name='center'><span>中间</span></slot> <slot name='right'><span>右边</span></slot> </div> </template>父组件 app:
<div id="app"> <cpn></cpn> <!-- 2.6.0更新后的插槽使用方式发生了变化 --> <!-- 区别在于调动的时候是使用 v-slot:具体名称,而不是定义一个 slot='具体名称' 这样的属性 --> <cpn> <!-- 注意:2.6.0 之后的这个写法中,v-slot:具体名称 只能写在 template 标签中,而废弃的写法可以写在某个具体的标签上面 --> <template v-slot:center> <!-- 指明使用的是哪个插槽 --> 用户名:<input type="text"> </template> </cpn> </div>效果图:

注意:v-slot只能添加在template上
作用域插槽
有时让插槽内容能够访问子组件中才有的数据是很有用的。但是由于子组件的作用域在子组件,而父组件的作用域在父组件,这样一来,父组件就访问不到子组件的信息了,但是我们又不想用$emit发送事件去传递信息,这个时候可以用作用域插槽来实现。**注意:**你不要以为这又是父传子的一种方式,因为这种方法仅限于在使用插槽的时候才有用,话不多说,看代码:
vm实例:
<script>
var vm = new Vue({
el: '#app',
data: {},
methods: {},
components: {
cpn: {
template: '#cpn',
data() {
return {
list: ['coderlyl', 'tom' , 'mack']
}
},
}
}
});
</script>
子组件 childCom:
<template id="cpn">
<div>
<slot :coderlyl='list'>
<!--list是子组件data中的数据,coderlyl是自己命名的变量,前面还有v-bind绑定-->
<ul>
<li v-for="(item, index) in list" :key="index">{{item}}</li>
</ul>
</slot>
</div>
</template>
父组件 app:
<div id="app">
<cpn></cpn>
<cpn>
<template v-slot='lyl'> <!--这里的lyl也是自己命名的-->
<span>{{lyl.coderlyl.join('--')}}</span>
</template>
</cpn>
</div>
效果图:
来源:CSDN
作者:努力学前端的阿龙
链接:https://blog.csdn.net/qq_42014236/article/details/104044830
