1.实现效果图
2.第一步,新建一个.vue文件 定义一个弹框的基本模板
style样式放在了文章的最底部,如果需要看效果,需要将样式放入这个vue文件里,样式是用less写的,需要你的项目引入less
注意:我这里的组件右上角关闭是一张图片 需要换成你自己本地的路径
{{title}}
{{content}}
3.定义一个js文件
import Vue from 'vue'; import Alert from '@/components/public/alertModal'; //引入刚才写的弹框组件 let AlertCOnstructor= Vue.extend(Alert); // 返回一个“扩展实例构造器” let AlertModal = (o) => { let alertDom = new AlertConstructor({ el: document.createElement('div'); //将Alert组件挂载到新创建的div上 }) document.body.appendChild(alertDom.$el); //把Alert组件的dom添加到body里 // 标题 alertDom.title = o.title || '信息'; // 单条内容 alertDom.cOntent= o.content; // 关闭按钮 alertDom.cancelBtn = o.cancelBtn; // 弹框三个事件 右上角关闭 确定 取消 alertDom.a_close = o.close || null; alertDom.a_cOnfirm= o.confirm || null; alertDom.a_cancel = o.cancel || null; } export default AlertModal;
4.mian.js
import alert from '@/common/alertModal' //这里引入的是js文件
Vue.prototype.$alert = alert;
5.在任意组件调用
取消按钮开启
调用之后是往body添加元素
5.通过window.alertIsShow,给window增加一个属性,来控制一个页面只会出现一个弹框
methods: { operate () { if (!window.alertIsShow) { // 弹框模板有个 delete window.alertIsShow 是为了弹框关闭之后能再次显示 this.$alert({ title: '信息', content: '登入成功!', cancelBtn: true, close () { // 这里执行点击右上角需要做的事,默认执行关闭弹框 }, confirm () { // 这里执行点击确定按钮需要做的事,默认执行关闭弹框 }, cancel () { // 这里执行点击取消按钮需要做的事,默认执行关闭弹框 } }) window.alertIsShow = true; } } }
6.最后是弹框组件的less样式
如果本篇文章对你有帮助的话,很高兴能够帮助上你。
补充知识:Vue注册全局组件-弹窗组件
在src目录下新建components文件夹
1.新建module文件夹,然后新建v-alert.vue
{{title}} {{titleData}}
2.在nodule同级目录新建vue-component.js
import VAlert from './v-alert'; //弹窗 export default { install(Vue) { Vue.component('VAlert', VAlert); } };
3.在main.js中注册为全局组件
import vueComponent from "./components/vue-component";
Vue.use(vueComponent);
4.在其他组件可以直接用了,无需import
以上这篇vue 实现一个简单的全局调用弹窗案例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。