使用vue封装一个消息提示组件

组件的代码和注释如下:如果有不明白的地方可以留言进行交流。

<!--
参数                  说明                                  类型                可选值        默认值
panelShape          panel的的宽高,请带单位                  Object                           width: '300px',
                                                                                            height: '220px'
                    传入(如vw、px)

isModal       是否展示提示框,在父组件要使用.sync            boolean                          false
              进行传值

duration      显示时间, 毫秒。设为 0 则不会自动关闭           number                           3000

 <slot name="content"></slot> 需要展示的内容

  使用例子如下:
    <Message :panelWidth="panelWidth" :isModal.sync="isModal">
      <template #content>
        <div class="panel-content">
        </div>
      </template>
    </Message>
    ...
      panelShape:{
        width: '300px',
        height: '220px'
      },
      isModal: false
-->

<template>
  <div class="message">
    <div class="shadow" :class="{'z-show':isModal}" @click="onClose"></div>
    <div
      class="panel"
      :style="{width:panelShape.width,height:panelShape.height}"
      :class="{'z-show':isModal}"
    >
      <slot name="content"></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: '',
  components: {},
  props: {
    panelShape: {
      type: Object,
      default: () => {
        return {
          width: '300px',
          height: '220px'
        }
      }
    },
    isModal: {
      type: Boolean,
      default: false
    },
    duration: {
      type: Number,
      default: 3000
    }
  },
  data () {
    return {}
  },
  mounted () {},
  watch: {
    isModal: {
      handler (val, oldVal) {
        if (val) {
          this.onCloseTime()
        }
      },
      deep: true
    }
  },
  methods: {
    // 关闭弹窗
    onClose () {
      // 子组件更新父组件的传值
      this.$emit('update:isModal', false)
    },
    // 设置关闭弹窗时间
    onCloseTime () {
      if (this.duration !== 0) {
        setTimeout(() => {
          this.$emit('update:isModal', false)
        }, this.duration)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.message {
  .shadow {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 3;
    background: rgba(0, 0, 0, 0.2);
    display: none;
  }
  .shadow.z-show {
    display: block;
  }
  .panel {
    position: fixed;
    top: -150px;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 5;
    overflow: hidden;
    background: rgba(255, 255, 255, 1);
    box-shadow: 0px 4px 64px 0px rgba(51, 55, 70, 0.37);
    border-radius: 10px;
    display: flex;
    align-content: center;
    transition: all 0.28s;
  }
  .panel.z-show {
    top: 50%;
  }
}
</style>

发布了53 篇原创文章 · 获赞 59 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42268364/article/details/105134926