vue学习笔记--插槽、具名插槽和作用域插槽

插槽使用场景是;如果子组件需要显示的内容并非来自本身,而是父组件传递进来的,而假如直接这样写,是不可以实现的,因为如果me-component没有包含一个 <slot> 元素,则任何传入它的内容都会被抛弃:

代码如下

me-component:

<template>
<div>
<p>你好</p>
<slot></slot>
</div>
</template>

<script>
export default {
name: "me-component"
}
</script>

<style scoped>

</style>

Home 组件:
<template>
<div class="home">
<me-component>我是header</me-component>

</div>
</template>

<script>
import meComponent from '../components/me-component'

export default {
name: 'home',
components: {
meComponent
},
}
</script>


具名插槽:
me-component:
<template>
<div>
<p>你好</p>
<p>你好</p>
<slot name="header"></slot>
<slot name="footer"></slot>
</div>
</template>

<script>
export default {
name: "me-component"
}
</script>

<style scoped>

</style>
Home 组件:

<template>
<div class="home">
<me-component>
<h1 slot="header">我是header</h1>
<h1 slot="footer">我是footerr</h1>
</me-component>

</div>
</template>

<script>
import meComponent from '../components/me-component'
export default {
name: 'home',
components: {
meComponent
},

}
</script>

参考文献:https://www.jianshu.com/p/d8401e291258
 
 
原文地址:https://www.cnblogs.com/zhx119/p/11039419.html