首页 > 语言 > JavaScript > 正文

vue组件化中slot的基本使用方法

2024-05-06 15:39:56
字体:
来源:转载
供稿:网友

前言

slot可以在子组件中开启插槽,在父组件引用该组建时,可以定义这个插槽内要展现的功能或模块,下面话不多说了,来一起看看详细的介绍吧

1.单个slot

子组件中在相应位置写slot标签,父组件在引用子组件时,在子组件标签内写要插入插槽的元素;

还可以设置slot在父组件没有设置插槽时,子组件的插槽默认显示内容;

父组件.vue

<template> <div class="home"> <child-componment>  <p>  这是父组件的slot替代内容!  </p> </child-componment> </div></template>​<script>import childComponment from '@/components/childComponment.vue'export default { name: "home", components:{ childComponment }, data(){ return { message: '' } }};</script>

子组件childComponment.vue

<template> <div class="childComponment"> <h2>这是子组件childComponment!</h2> <slot>  <span style="color: red;">如果父组件没有插入内容,我这样可以设置默认的显示内容</span> </slot> </div></template>​<script>export default { name: "childComponment", data(){ return {  message: '' } }};</script>

2.具名slot(同时使用多个插槽)

给slot指定一个名称,可以分发多个slot插槽,但是只能有一个无名slot;

父组件的slot插槽内容,不写slot="xxx"的都会插到子组件的无名slot中;

如果没有指定无名slot(默认slot),父组件内多余的内容将会被抛弃。

<template> <div class="home"> <child-componment>  <h1 slot="header">  父组件的header  </h1>  <h6 slot="footer">父组件的footer</h6>    <h6>父组件的无名slot-1</h6>  <p>  父组件的无名slot-2  </p> </child-componment> </div></template>​<script>import childComponment from '@/components/childComponment.vue'export default { name: "home", components:{ childComponment }, data(){ return {  message: '' } }};</script>

子组件

<template> <div class="childComponment"> <span>这是子组件childComponment的正常内容!</span> <div class="header">  <slot name="header">  <span style="color: red;">子组件默认header-slot</span>  </slot> </div> <div class="container">  <!-- 如果没有指定无名slot(默认slot),父组件内多余的内容将会被抛弃 -->  <slot>  <span style="color: red;">子组件默认无名slot</span>  </slot> </div> <div class="footer">  <slot name="footer">  <span style="color: red;">子组件默认footer-slot</span>  </slot> </div> </div></template>​<script>export default { name: "childComponment", data(){ return {  message: '' } }};</script><style scoped>.childComponment{ font-size: 16px;}.header{ height: 100px; border:1px solid red; color: red;}.container{ height: 500px; border: 1px solid black; color: black;}.footer{ height:100px; border: 1px grey solid; color: grey;}</style>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选