bekacodechn
5/14/2019 - 7:48 AM

alert.md

如何使用?

alert.js导入到main.js中,并将alert注册到Vue实例

Vue.prototype.$Alert = alert  
this.$Alert.info({content: 'xxxxx', duration: 2000})

alert.vue

<template>
  <div class="alert">
    <div class="alert-main" v-for="item in notices" :key="item.name">
      <div class="alert-content">{{item.content}}</div>
    </div>
  </div>
</template>

<script>
let seed = 0;
//负责唯一id
function getUid() {
  return "alert_" + seed++;
}
export default {
  name: "alert",
  data() {
    return {
      notices: []
    };
  },
  methods: {
    add(notice) {
      const name = getUid();
      let _notice = Object.assign({ name }, notice);
      this.notices.push(_notice);
      let d = notice.duration;
      setTimeout(() => {
        this.remove(name);
      }, d);
    },
    remove(name) {
      const notices = this.notices;
      for (let i = 0; i < notices.length; i++) {
        if (notices[i].name === name) {
          this.notices.splice(i, 1);
          break;
        }
      }
    }
  }
};
</script>
<style lang='scss' scoped>
.alert {
  position: fixed;
  width: 100%;
  top: 16px;
  left: 0;
  text-align: center;
  pointer-events: none;
}
.alert-content {
  display: inline-block;
  padding: 8px 16px;
  background: #fff;
  border-radius: 3px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.2);
  margin-bottom: 8px;
}
</style>

notifacation.js

import Vue from 'vue'
import Alert from './alert.vue'

Alert.newInstance = props => {
    const instance = new Vue({
        data() {
            return {
                props
            }
        },
        render: h => {
            return h(Alert, {
                props: props
            })
        }
    })
    const component = instance.$mount()
    document.body.appendChild(component.$el)
    // 因为只有一个chirdren, [0]就能拿到alert组件实例
    const alert = instance.$children[0]

    return {
        add(notice) {
            alert.add(notice)
        },
        remove(name) {
            alert.remove(name)
        }
    }
}

export default Alert

alert.js

import Notification from './notification'

let messageInstance = null;
// 单例
function getMessageInstance() {
    messageInstance = messageInstance || Notification.newInstance()
    return messageInstance
}

function notice({ duration = 15, content = '' }) {
    let instance = getMessageInstance()
    instance.add({
        duration: duration,
        content: content
    })
}

export default {
    info(options) {
        notice(options)
    }
}