记录下学习过程。

本人新手,边学边整理记录,所以代码可能写的不怎么优雅,函数名、变量名也有点乱,暂时不要在意这些细节。

想要达到的效果:像element ui的message一样能全局this.$myMessage调用

Vue2封装自己的全局message插件_Vue2

Vue2封装自己的全局message插件_Vue2_02

1、编写myLayer.vue

定义了弹窗的布局和基本属性。放在src/components目录下。

<template>
<div class="modal" v-if="visible" @click.stop="modalClick">
<div class="container" ref="container" id="container" @click.stop="">
<!-- 图标区 -->
<div class="iconDiv">
</div>

<!-- 消息 -->
<div class="message">{{ message }}</div>

<!-- 按钮 -->
<div class="layerButtonContainer" v-if="type == 'question'">
<div class="layerButton" @click="clickNo" style="color: #F56C6C;">否</div>
<div class="layerButton" @click="clickYes"
style="color: #409EFF; border-left: solid 1px #DCDFE6;">是</div>
</div>
</div>
</div>
</template>

<script>
export default {
data() {
return {
visible:false,
message:'',
type:'message', //loading, success, error, warning, question, message
callBack: null, //询问框点击是时的回调函数
}
},
methods: {
modalClick() {
if (this.type != 'loading') {
this.visible=false;
}
},
clickYes(){
if(typeof this.callBack === 'function'){
this.callBack();
}
this.visible=false;
},
clickNo(){
this.visible=false;
},
},
computed: {

},
mounted() {

},
}

</script>

2、myLayer.js

放在src/plugins目录下。


import myLayer from '../components/myLayer.vue'

let instance; //创建myLayer组件的一个实例
export default {
install(Vue, options) {
if (!instance) {
const layerConstructor = Vue.extend(myLayer);
instance = new layerConstructor({
el: document.createElement('div')
});
document.body.appendChild(instance.$el);
}

instance.visible = false;

let layer = {
success(msg = '操作成功') {
instance.message = msg;
instance.type = 'success';
instance.visible = true;
setTimeout(() => {
instance.visible = false;
}, 1750);
},
loading(msg = '请稍后...') {
instance.message = msg;
instance.type = 'loading';
instance.visible = true;
},
error(msg = '操作失败') {
instance.message = msg;
instance.type = 'error';
instance.visible = true;
},
warning(msg = '警告') {
instance.message = msg;
instance.type = 'warning';
instance.visible = true;
},
question(msg, callBack) {
instance.message = msg;
instance.type = 'question';
instance.callBack = callBack;
instance.visible = true;
},
message(msg = '普通消息') {
instance.message = msg;
instance.type = 'message';
instance.visible = true;
},
close() {
instance.visible = false;
},
};

if (!Vue.$layer) {
Vue.$layer = layer;
}

Vue.mixin({
created() {
this.$layer = Vue.$layer;
}
});
}
}

3、main.js

在main.js里引入并使用myLayer.js

import myLayer from './plugins/myLayer';
Vue.use(myLayer);

ok了。

现在可以在任何组件中直接使用myLayer,例如:

this.$layer.success('注册成功!');

Vue2封装自己的全局message插件_全局组件_03

this.$layer.question('是否确定删除?', ()=>{
console.log('点击了【是】');
//其他操作
});

Vue2封装自己的全局message插件_全局组件_04

this.$layer.loading('正在加载...');
let that = this;
setTimeout(() => {
that.$layer.close();
}, 2000);

Vue2封装自己的全局message插件_全局组件_05