什么是作用域插槽?
在父子组件中,子组件可以拿到父组件的数据,然而父组件调用子组件时,是无法直接访问子组件中的值,因为父级模板里的所有内容都是在父级作用域中编译的,而子组件所有内容都是在子作用域中编译的。在很多时候,需要在插槽中访问子组件作用域内的数据,就需要用到作用域插槽,
作用域插槽简答来说就是 父组件可以访问子组件的数据,
如何使用
首先需要在<slot>标签上绑定两个元素
1,name属性
2,v-bind :titleVlaue ='title',titleVlaue是要传给父组件的变量名,tltle父组件传过来的内容(v-bind可省略为:)
//子组件
<template>
<div>
<h3>
<slot name="title" v-bind:titleValue="title">{{ title }}</slot>
</h3>
<h4 v-for="item in list" :key="item.id">
<slot name="text" :textValue="item">{{ item.id }}{{ item.text }}</slot>
</h4>
</div>
</template>
<script>
export default {
props: ['list', 'title']
}
</script>
<style></style>
v-slot:title="slotTitle"中,title是子组件中定义的slot插槽名,不要混淆,
slotTitle是接受子组件数据的变量名,根据需求起(随便起)
可在分别对应具的具名插槽内添加内容,
控制内容的展示如不展示编号1,2,3
父组件
<template>
<div>
<e :list="list" :title="title">
<template v-slot:text="slotTitle">
{{ slotTitle.textValue.text }}
</template>
</e>
</div>
</template>
<script>
import e from "./e.vue";
export default {
components: { e },
data() {
return {
teext: '1',
layout: {
header: '头部',
footer: '脚部'
}, title: '名人名言',
list: [
{
id: 1,
text: '要成功,先发疯,头脑简单向前冲'
}, {
id: 2,
text: '不能天生丽质就只能天生励志!'
}, {
id: 3,
text: '世上唯一不能复制的是时间,唯一不能重演的是人生。'
}
]
}
}
}
</script>
<style lang="scss" scoped></style>
为title添加图标
父组件
<template>
<div>
<e :list="list" :title="title">
<template v-slot:title="slotTitle">
<i class="el-icon-guide"></i>{{ slotTitle.titleValue }}
</template>
//可用结构赋值简写为:titleValue="{titleValue }"
<template :titleValue="{titleValue }">
<i class="el-icon-guide"></i>{{ titleValue }}
</template>
</e>
</div>
</template>