父组件:
<template>
<div>
<div>
<h1>我是头部</h1>
<slot name="head"></slot>
</div>
<div>
<h1>我是尾部</h1>
<slot name="footer"></slot>
</div>
</div>
</template>
<script>
export default {
data() {
return {}
}
}
</script>
子组件:
<template>
<div id="app">
<Index>
<template v-slot:footer>
<p>这里是footer</p>
</template>
<template v-slot:head>
<p>这里是head</p>
</template>
</Index>
</div>
</template>
<script>
import Index from ‘./components/index.vue‘
export default {
name: ‘app‘,
components: {
Index
}
}
</script>
接下来我们将子组件插槽的名字调换一下,父组件不变
<template>
<div id="app">
<Index>
<template v-slot:head>
<p>这里是head</p>
</template>
<template v-slot:footer>
<p>这里是footer</p>
</template>
</Index>
</div>
</template>
<script>
import Index from ‘./components/index.vue‘
export default {
name: ‘app‘,
components: {
Index
}
}
</script>
<template>
<div id="app">
<Index>
<template v-slot:footer>
<p>这里是footer</p>
</template>
<template v-slot:head>
<p>这里是head</p>
</template>
<template>
<p>这里是默认插槽</p>
<p>aaaaa</p>
</template>
</Index>
</div>
</template>
<script>
import Index from ‘./components/index.vue‘
export default {
name: ‘app‘,
components: {
Index
}
}
</script>
父组件插槽:
<template>
<div>
<div>
<h1>我是头部</h1>
<slot name="head"></slot>
</div>
<div>
<h1>我是默认插槽</h1>
<slot></slot>
</div>
<div>
<h1>我是尾部</h1>
<slot name="footer"></slot>
</div>
</div>
</template>
<script>
export default {
data() {
return {}
}
}
</script>
注意:
父级的填充内容如果指定到子组件的没有对应名字插槽,那么该内容不会被填充到默认插槽中。
如果子组件没有默认插槽,而父级的填充内容指定到默认插槽中,那么该内容就“不会”填充到子组件的任何一个插槽中
如果子组件有多个默认插槽,而父组件所有指定到默认插槽的填充内容,将“会” “全都”填充到子组件的每个默认插槽中。
原文:https://www.cnblogs.com/cc0419/p/12545941.html