插槽大体分为:
- 默认插槽
- 具名插槽
- 作用域插槽
插槽用于单独公用组件
例子:
- 组件中有标签或者值时 值,子组件如不使用slot将不会显示-----值
- 组件中有标签或值 值,子组件使用将会显示-----值
父组件
<template>
<div>
我是父组件
<Index2><div>值</div></Index2>
</div>
</template>
<script>
import Index2 from "./index2";
export default {
components: { Index2 },
};
</script>
子组件
<template>
<div>
我是子组件
<!--有<slot></slot>才会对应显示父组件<div>值</div>-->
<slot></slot>
</div>
</template>
默认插槽
- 父组件有标签或者值值,子组件使用值2将会显示------值,值2不会显示
- 父组件没有标签或者值,子组件使用值2将会显示-----值2
- 注:父组件内有值,一律用父组件的值,父组件未有之则使用子组件的值
父组件
<template>
<div>
我是父组件
<!-- <Index2><div>值</div></Index2> -->
<!-- <Index2></Index2> -->
</div>
</template>
<script>
import Index2 from "./index2";
export default {
components: { Index2 },
};
</script>
子组件
<template>
<div>
我是子组件
<!-- <slot></slot> -->
<!-- <slot>值2</slot> -->
</div>
</template>
具名插槽
v-slot 只能添加在 template上 具名插槽在书写的时候可以使用缩写,v-slot用#来代替 父组件
<template>
<div>
我是父组件
<div class="container">
<Index2>
<template #header>
<p>这是页眉</p>
</template>
<div>正文</div>
<template v-slot:footer>
<p>这是页脚</p>
</template>
</Index2>
</div>
</div>
</template>
<script>
import Index2 from "./index2";
export default {
components: { Index2 },
};
</script>
子组件
<template>
<div>
我是子组件
<!-- name名称自行定义对应v-solt -->
<div class="container">
<header>
<slot name="header">header</slot>
</header>
<main>
<!-- 不添加name默认添加 v-slot:default -->
<slot>main</slot>
</main>
<footer>
<slot name="footer">footer</slot>
</footer>
</div>
</div>
</template>
<script>
作用域插槽(子组件的值共享给父组件)默认插槽的缩写语法不能和具名插槽混用,因为作用域会不明确
父组件
<template>
<div>
我是父组件
<Index3>
<!-- <template v-slot:aa="custom1">
{{ custom1.test1.one }}
</template> -->
<!-- 默认 -->
<!-- <template v-slot:default="custom2">
{{ custom2.test2.two }}
</template> -->
<!-- 默认缩写 -->
<!-- <template v-slot="custom3">
{{ custom3.test2.two }}
</template> -->
<!-- 解构写法 -->
<!-- <template v-slot:aa="{ test1 }">
{{ test1.one }}
</template> -->
<template #aa="{ test1 }">
{{ test1.one }}
</template>
</Index3>
</div>
</template>
<script>
import Index3 from "./index3";
export default {
components: {Index3 },
};
</script>
子组件
<template>
<div>
我是子组件
<!-- name名称自定义对应v-slot -->
<slot v-bind:test1="test" name="aa"></slot>
<slot v-bind:test2="test"></slot>
</div>
</template>
<script>
export default {
data() {
return {
test: {
one: 1,
two: 2,
},
};
},
};
</script>