Element-UI源码学习——弹框组件

手写弹框组件


前言

首先,分析一下Element-UI的对话框,点击,会弹出一个对话框。对话框由具体的弹框内容、关闭或确认按钮、外围的遮罩层组成。首先,先看下elmentui的用法:

一、Element-UI的弹框

el-dialog组件里面可进行配置

<el-dialog
    v-model="dialogVisible"
    title="Tips"
    width="30%"
    :before-close="handleClose"
  >
    <span>This is a message</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="dialogVisible = false"
          >Confirm</el-button
        >
      </span>
    </template>
  </el-dialog>

效果:
在这里插入图片描述

二、如何自己手写?

1、dom实现:
外面的div实现遮罩层,里面的div是具体的内容

<div class="el_dialog">
   <div class="el_dialog__content">
        <slot/>
    </div>
</div>

css:

.el_dialog {
        position: fixed;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        margin: 0;
        padding: 0;
    }
    .el_dialog__content {
        width: v-bind(width1);
        height: 400px;
        background-color: white;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }

2、弹框类的组件都需要直接渲染在body标签下面。因为弹框类组件都是绝对定位,如果在组件内部渲染,组件的css属性会影响弹框组件的渲染样式(可以尝试下,比如会出现浮动等),为了避免这种问题的出现,弹窗组件Dialog、Notification都需要渲染在body内部。
怎么渲染呢?可以使用vue3自带的Teleport,可以很方便地渲染到body上:

<template>
    <teleport
        to="body"
    >
        <div class="el_dialog">
            <div class="el_dialog__content" :style="DialogStyle">
                <slot/>
            </div>
        </div>
    </teleport>
</template>

3、为了使样式可以可配置,可以在使用组件时传入一个对象,这个对象里面包含了样式,然后在组件中绑定这个样式:

<template>
    <teleport
        to="body"
    >
        <div class="el_dialog">
            <div class="el_dialog__content" :style="DialogStyle">
                <slot/>
            </div>
        </div>
    </teleport>
</template>
<script>
export default {
  name:'Dialog',
  props: {
    DialogStyle: {
      type: Object,
      default: function () {
        return {
            width: '800px',
            height: '400px',
            'background-color': 'white',
            display: 'flex',
            'flex-direction': 'column',
            'justify-content': 'center',
            'align-items': 'center'
        };
      },
    },
  }
}
</script>

实现效果:
在这里插入图片描述

弹框组件到此结束,全部代码可以从这下载https://github.com/LisaNcu/myElementUI.git

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值