vue弹窗组件
2018-09-03 13:49 muamaker 阅读(2749) 评论(0) 编辑 收藏 举报文件结构
component.vue
<template> <div class="_vuedals" v-show="show"> <component v-if="options.component" :is="options.component" v-bind="options.props" v-on="options.events" ref="modalessComponent" ></component> </div> </template> <script> import Bus from "./bus.js"; export default { name:"vuedals", data(){ return{ options:{}, show:false } }, created(){ var me = this; var defval = { props:[], } Bus.$on("open",function(options){ me.options = options; me.show = true; }); Bus.$on("close",function(options){ me.show = false; }); }, mounted(){ }, methods:{ } } </script> <style> ._vuedals{ position: absolute; top: 0; left: 0; z-index: 1000; width: 100%; height: 100%; background: rgba(0,0,0,0.4); } </style>
bus.js
let instance = null; class EventBus { constructor() { if (!instance) { this.events = {}; instance = this; } return instance; } $emit(event, message) { if (!this.events[event]) return; const callbacks = this.events[event]; for (let i = 0, l = callbacks.length; i < l; i++) { const callback = callbacks[i]; callback.call(this, message); } } $on(event, callback) { if (!this.events[event]) this.events[event] = []; this.events[event].push(callback); } } export default new EventBus();
index.js
import Bus from './bus'; import Component from './component.vue'; export default { install(Vue) { // Global $vuedals property Vue.prototype.$vuedals = new Vue({ name: '$vuedals', created() { }, methods: { open(options = null) { Bus.$emit('open', options); }, close(data = null) { Bus.$emit('close', data); } } }); Vue.component('vuedals', Component); } };
使用:
一、引入
import vuedals from './components/vuedals'
Vue.use(vuedals);
二、调用
import box from '../components/box.vue';
this.$vuedals.open({ component:box, //引入的模板文件 props:{title:"这是一个title"}, events:{ myEvent:function(){ console.log("myEvent....") } } })
其中box.vue为
<template> <div class="box"> 这里是弹出层的内容 <p>{{title}}</p> <li @click="myEvent">点击我</li> <li @click="close">关闭弹出层</li> </div> </template> <script> export default { name: 'box', data () { return { msg: '' }; }, props:["title"], methods: { myEvent:function(){ this.$emit("myEvent",{}); }, close:function(){ console.log(this.$vuedals.close()) } } }; </script> <style> .box{ margin: 40% auto 0; width: 80%; height: 200px; background: #fff; border-radius: 10px; } </style>
效果: