Currently when developing a personal blog project, I was not prepared to use some of the more popular UI libraries from the beginning (after all, it is a personal project, so I need to practice more. Okay), so you need to develop several global components yourself. Here we take MessageBox as an example to record how Vue.js develops global components.
Talk is cheap. Show me the code.
// /src/components/MessageBox/index.vue
{{ title }}
{{ content }}
vue.js official documentation has an introduction to developing plug-ins. The specific implementation code is as follows:
// /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);
According to the previous definition A good method, you can happily call this component in various pages.
this.$msgBox.showMsgBox({
title: '添加分类',
content: '请填写分类名称',
isShowInput: true
}).then(async (val) => {
// ...
}).catch(() => {
// ...
});
##The above content is Vue. js to develop a globally called MessageBox component, I hope it will be helpful to everyone.
Related recommendations:
vue.js implementation method of parent passing parameters to child components
Detailed analysis of several postures in Vue.js component communication
Detailed learning of common instructions in Vue.js
The above is the detailed content of Vue.js develops a globally called MessageBox component. For more information, please follow other related articles on the PHP Chinese website!