最近学习了Vue.js,感觉组件这个地方知识点挺多的,而且很重要,所以决定记录下,下面这篇文章主要给大家介绍了关于利用vue.js开发实现全局调用的MessageBox组件的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面来一起看看吧。
前言
一开始接触到vue中的组件的时候,对于组件的理解还是不够充分的,最近在开发个人博客项目中,一开始就没准备使用一些现在比较流行的UI库(毕竟是个人项目,多练练手还是好的),所以需要自己开发几个全局组件,这里以MessageBox为例记录下vue.js如何开发全局组件。所谓全局变量是针对vue实例下说的,即所有的vue实际都可以运用到这个组件,局部组件就是针对某个实例来说的,只有这个vue实例下才能发挥作用,下面话不多说了,来一看看详细的介绍吧。
源码
github地址:Talk is cheap. Show me the code.
本地下载地址:http://xiazai.gaodaima.com/201711/yuanma/vue-messagebox(gaodaima.com).rar
组件模板
// /src/components/MessageBox/index.vue <div class="message-box"> <div class="mask"></div><div class="message-content"> <h3 class="title">{{ title }}</h3><p class="content">{{ content }}</p><div> </div><div class="btn-group"> <button class="btn-default">{{ cancelBtnText }}</button><button class="btn-primary btn-confirm">{{ confirmBtnText }}</button></div></div></div> // 此处省略 ...
给组件添加全局功能
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, instance; const initInstance = () => { // 实例化vue实例 currentMsg = new MessageBoxInstance(); let msgBoxEl = currentMsg.$mount().$el; document.body.appendChild(msgBoxEl); }; // 在Vue的原型上添加实例方法,以全局调用 Vue.prototype.$msgBox = { showMsgBox (options) { if (!instance) { initInstance(); } if (typeof options === 'string') { currentMsg.content = options; } else if (typeof options === 'object') { Object.assign(currentMsg, options); } return currentMsg.showMsgBox(); } }; }; 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(() => { // ... });
最后来张效果图
本文来源gao@daima#com搞(%代@#码网@总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对gaodaima搞代码网的支持。
以上就是vue.js开发实现全局调用的MessageBox组件实例代码的详细内容,更多请关注gaodaima搞代码网其它相关文章!