前言
目前在开发个人博客项目中,一开始就没准备使用一些现在比较流行的ui库(毕竟是个人项目,多练练手还是好的),所以需要自己开发几个全局组件,这里以messagebox为例记录下vue.js如何开发全局组件。
源码
Talk is cheap. Show me the code.
组件模板
// /src/components/MessageBox/index.vue
{{ title }}
{{ content }}
给组件添加全局功能
vue.js官方文档中有开发插件的介绍。具体实现代码如下:
// /src/components/MessageBox/index.js
import msgboxVue from './index.vue';
// 定义插件对象
const MessageBox = {};
// vue的install方法,用于定义vue插件
MessageBox.install = function (Vue, options) {
const MessageBoxInstance = Vue.extend(msgboxVue);
let currentMsg;
const initInstance = () => {
// 实例化vue实例
currentMsg = new MessageBoxInstance();
let msgBoxEl = currentMsg.$mount().$el;
document.body.appendChild(msgBoxEl);
};
// 在Vue的原型上添加实例方法,以全局调用
Vue.prototype.$msgBox = {
showMsgBox (options) {
if (!currentMsg) {
initInstance();
}
if (typeof options === 'string') {
currentMsg.content = options;
} else if (typeof options === 'object') {
Object.assign(currentMsg, options);
}
return currentMsg.showMsgBox()
.then(val => {
currentMsg = null;
return Promise.resolve(val);
})
.catch(err => {
currentMsg = null;
return Promise.reject(err);
});
}
};
};
export default MessageBox;
全局使用
// src/main.js
import MessageBox from './components/MessageBox/index';
Vue.use(MessageBox);
页面调用
按照之前定义好的方法,可以在各个页面中愉快的调用该组件了。
立即学习“前端免费学习笔记(深入)”;
this.$msgBox.showMsgBox({
title: '添加分类',
content: '请填写分类名称',
isShowInput: true
}).then(async (val) => {
// ...
}).catch(() => {
// ...
});
最后来张效果图

Ke361是一个开源的淘宝客系统,基于最新的ThinkPHP3.2版本开发,提供更方便、更安全的WEB应用开发体验,采用了全新的架构设计和命名空间机制, 融合了模块化、驱动化和插件化的设计理念于一体,以帮助想做淘宝客而技术水平不高的朋友。突破了传统淘宝客程序对自动采集商品收费的模式,该程序的自动 采集模块对于所有人开放,代码不加密,方便大家修改。集成淘点金组件,自动转换淘宝链接为淘宝客推广链接。K
以上内容就是Vue.js开发一个全局调用的MessageBox组件,希望对大家有帮助。
相关推荐:









