Vue $mount實戰(zhàn)之實現(xiàn)消息彈窗組件
更新時間:2019年04月22日 10:43:19 作者:heath_learning
這篇文章主要介紹了Vue $mount實現(xiàn)消息彈窗組件的相關知識,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
之前的項目一直在使用Element-UI框架,element中的Notification、Message組件使用時不需要在html寫標簽,而是使用js調(diào)用。那時就很疑惑,為什么element ui使用this.$notify、this.$message就可以實現(xiàn)這樣的功能?
1、實現(xiàn)消息彈窗組件的幾個問題
- 如何在任何組件中使用this.$message就可以顯示消息?
- 如何將消息的dom節(jié)點插入到body中?
- 同時出現(xiàn)多個消息彈窗時,消息彈窗的z-index如何控制?
2、效果預覽

3、代碼實現(xiàn)
PMessage.vue
<template>
<transition name="message-fade">
<div class="p-message"
:class="[type, extraClass]"
v-show="show"
@mouseenter="clearTimer"
@mouseleave="startTimer">
<div class="p-message-container">
<i class="p-message-icon" :class="`p-message-icon-${type}`"></i>
<div class="p-message-content">
<slot class="p-message-content">
<div v-html="message"></div>
</slot>
</div>
</div>
</div>
</transition>
</template>
<script>
// 綁定事件
function _addEvent(el, eventName, fn){
if(document.addEventListener){
el.addEventListener(eventName, fn, false);
}else if(window.attachEvent){
el.attactEvent('on' + eventName, fn);
}
};
// 解綁事件
function _offEvent(el, eventName, fn){
if(document.removeEventListener){
el.removeEventListener(eventName, fn, false);
}else if(window.detachEvent){
el.detachEvent('on' + eventName, fn);
}
};
export default {
name: "PMessage",
data(){
return {
type: 'success',
duration: 3000,
extraClass: '',
message: '',
timer: null,
closed: false,
show: false
}
},
methods: {
startTimer(){
if(this.duration > 0){
this.timer = setTimeout(() => {
if(!this.closed){
this.close();
}
}, this.duration);
}
},
clearTimer(){
clearTimeout(this.timer);
},
close(){
this.closed = true;
if(typeof this.onClose === 'function'){
// 調(diào)用onClose方法,以從p-message.js中的instances數(shù)組中移除當前組件,不移除的話就占空間了
this.onClose();
}
},
// 銷毀組件
destroyElement(){
_offEvent(this.$el, 'transitionend', this.destroyElement);
// 手動銷毀組件
this.$destroy(true);
this.$el.parentNode.removeChild(this.$el);
},
},
watch: {
// 監(jiān)聽closed,如果它為true,則銷毀message組件
closed(newVal){
if(newVal){
this.show = false;
// message過渡完成后再去銷毀message組件及移除元素
_addEvent(this.$el, 'transitionend', this.destroyElement);
}
}
},
mounted() {
this.startTimer();
}
}
</script>
<style lang="stylus">
@import "p-message.styl"
</style>
p-message.js
import Vue from 'vue';
import PMessage from './PMessage.vue';
import {popupManager} from "../../common/js/popup-manager";
let PMessageControl = Vue.extend(PMessage);
let count = 0;
// 存儲message組件實例,如需有關閉所有message的功能就需要將每個message組件都存儲起來
let instances = [];
const isVNode = function (node) {
return node !== null && typeof node === 'object' && Object.prototype.hasOwnProperty.call(node, 'componentOptions');
};
const Message = function (options) {
options = options || {};
if(typeof options === 'string'){
options = {
message: options
};
}
let id = 'message_' + ++count;
let userOnClose = options.onClose;
// PMsesage.vue銷毀時會調(diào)用傳遞進去的onClose,而onClose的處理就是將指定id的message組件從instances中移除
options.onClose = function (){
Message._close(id, userOnClose);
};
/* 這里傳遞給PMessageControl的data不會覆蓋PMessage.vue中原有的data,而是與PMessage.vue中原有的data進行合并,類似
* 與mixin,包括傳遞methods、生命周期函數(shù)也是一樣 */
let instance = new PMessageControl({
data: options
});
// 傳遞vNode
if(isVNode(instance.message)){
instance.$slots.default = [instance.message];
instance.message = null;
}
instance.id = id;
// 渲染元素,隨后使用原生appendChild將dom插入到頁面中
instance.$mount();
let $el = instance.$el;
// message彈窗的z-index由popupManager來提供
$el.style.zIndex = popupManager.getNextZIndex();
document.body.appendChild($el);
// 將message顯示出來
instance.show = true;
console.log(instance)
instances.push(instance);
return instance;
};
// message簡化操作
['success','error'].forEach(function (item) {
Message[item] = options => {
if(typeof options === 'string'){
options = {
message: options
}
}
options.type = item;
return Message(options);
}
});
/**
* 從instances刪除指定message,內(nèi)部使用
* @param id
* @param userOnClose
* @private
*/
Message._close = function (id, userOnClose) {
for(var i = 0, len = instances.length; i < len; i++){
if(instances[i].id === id){
if(typeof userOnClose === 'function'){
userOnClose(instances[i]);
}
instances.splice(i, 1);
break;
}
}
};
// 關閉所有message
Message.closeAll = function () {
for(var i = instances.length - 1; i >= 0; i--){
instances.close();
}
};
export default Message;
popup-manager.js
let zIndex = 1000;
let hasZIndexInited = false;
const popupManager = {
// 獲取索引
getNextZIndex(){
if(!hasZIndexInited){
hasZIndexInited = true;
return zIndex;
}
return zIndex++;
}
};
export {popupManager};
p-index.js
import pMessage from './p-message.js';
export default pMessage;
p-message.styl
.p-message{
position: fixed;
top: 20px;
left: 50%;
padding: 8px 15px;
border-radius: 4px;
background-color: #fff;
color: #000;
transform: translateX(-50%);
transition: opacity .3s, transform .4s;
&.message-fade-enter,
&.message-fade-leave-to{
opacity: 0;
transform: translateX(-50%) translateY(-30px);
}
&.message-fade-enter-to,
&.message-fade-leave{
opacity: 1;
transform: translateX(-50%) translateY(0);
}
&.error{
color: #ff3737;
}
.p-message-icon{ /* 使圖標與內(nèi)容能夠垂直居中 */
display: table-cell;
vertical-align: middle;
width: 64px;
height: 45px;
&.p-message-icon-success{
background: url("../../assets/images/icons/message-icon/icon_success.png") no-repeat 0 0;
}
&.p-message-icon-error{
background: url("../../assets/images/icons/message-icon/icon_error.png") no-repeat 0 0;
}
}
.p-message-content{ /* 使圖標與內(nèi)容能夠垂直居中 */
display: table-cell;
vertical-align: middle;
padding-left: 15px;
}
}
main.js
// 引入pMessage組件 import pMessage from './components/p-message/p-index.js'; // 將pMessage綁定到Vue.prototype中。這樣在組件中就可以通過this.$pMessage()的形式來使用了 Vue.prototype.$pMessage = pMessage;
相關文章
Vue動態(tài)權限登錄實現(xiàn)(基于路由與角色)
很多應用都會需要對不同的用戶進行權限控制,本文主要介紹了Vue動態(tài)權限登錄實現(xiàn)(基于路由與角色),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-05-05
vue v-for出來的列表,點擊某個li使得當前被點擊的li字體變紅操作
這篇文章主要介紹了vue v-for出來的列表,點擊某個li使得當前被點擊的li字體變紅操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07
Vue利用localStorage本地緩存使頁面刷新驗證碼不清零功能的實現(xiàn)
這篇文章主要介紹了Vue利用localStorage本地緩存使頁面刷新驗證碼不清零功能的實現(xiàn),本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09

