vue插件形式弹窗提示组件全局

38次阅读

共计 2240 个字符,预计需要花费 6 分钟才能阅读完成。

// 在组件文件建一个 notice 文件,文件中包含 index.j, notice.vue

index.js

import Vue from 'vue'
const NoticeConstructor = Vue.extend(require('./notice.vue').default)

let nId = 1;
const Notice = (option) => {
  let id = 'notice-' + nId++

  const NoticeInstance = new NoticeConstructor({
    data: {
      content: option.message,
      type: option.type
    }
  }) // 实例化一个带有 content 内容的 Notice
  NoticeInstance.id = id
  NoticeInstance.$mount() // 挂载但是并未插入 dom,是一个完整的 Vue 实例
  NoticeInstance.visible = true
  let noticeDom = NoticeInstance.$el
  document.body.appendChild(noticeDom) // 将 dom 插入 body
  NoticeInstance.$el.style.zIndex = nId + 10000
  return NoticeInstance
}

export default {
  install: Vue => {Vue.prototype.$notice = Notice}
}

notice.vue

<template>
  <transition name="message-fade">
    <div :class="['message','notice-'+type]" v-show="visible">
      <i :class="'el-icon-'+type"></i>
      <div :class="['content','content-'+type]">{{content}}</div>
    </div>
  </transition>
</template>

<script>
export default {data () {
    return {
      content: '',
      duration: 1000,
      visible: false,
      type: 'info',//'success','warning','error'
      hasClose: false,
      noticeTimer: null,
    }
  },
  mounted () {this.close()
  },
  methods: {close () {setTimeout(() => {
        this.visible = false
        setTimeout(() => {this.$destroy(true)
          this.$el.parentNode.removeChild(this.$el)
        }, 800)
      }, this.duration);
    }
  }
}
</script>

<style scoped lang="scss">
.message {
  position: absolute;
  top: 12vh;
  left: 50%;
  padding: 20px 30px;
  border-radius: 8px;
  background-color: #fff;
  transform: translateX(-50%);
  transition: opacity 0.3s, transform 0.4s;
  font-size: 30px;
}
.content {
  display: inline-block;
  margin-left: 12px;
  min-width: 380px;
}
/* .#2ed573 */
.notice-success {
  background-color: #f0f9eb;
  border-color: #e1f3d8;
}
.el-icon-success, .content-success {color: #67c23a;}
.notice-warning {
  background-color: #fdf6ec;
  border-color: #faecd8;
}
.notice-warning .content-warning {color: #e6a23c;}
.notice-error {
  background-color: #fef0f0;
  border-color: #fde2e2;
}
.notice-error .content-error {color: #f56c6c;}

// donghua
.message-fade-enter,
.message-fade-leave-to {
  opacity: 0;
  transform: translateX(-50%) translateY(-12vh);
}
.message-fade-enter-to,
.message-fade-leave {
  opacity: 1;
  transform: translateX(-50%) translateY(0px);
}

 .message-fade-enter-active {transition: all .5s ease;}
.message-fade-leave-active {transition: all .5s cubic-bezier(1.0, 0.2, 0.8, 1.0);
}


</style>

在 main.js
import Notice from '@/components/notice' // 这个是 index.js
Vue.use(Notice)
这样就可以在任何 vue 文件中引用了

          this.$notice({
            message: '提交成功!',
            type: 'success'
          });

正文完
 0