vue 自定义全局弹窗组件
问题描述: vue 自定义类似 elementUI 的 this.$confirm
解决方案: 通过vue 的extend 方法实现 然后全局注入
代码实现:
1. 展示的组件 (就是最基本的vue组件代码)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | < template > < a-modal title="" :visible="dialogVisible" width="416px" @cancel="handleClose" :closable="false" > < div class="confirm-box"> < div class="confirm-title"> < img src="@/assets/img/ihotel.png" alt=""> < span >酒店接口服务V2.1.0.14</ span > </ div > < div class="confirm-context"> {{message}},请稍后重试,如持续未恢复正常,请联系我们:400-9696-978</ div > </ div > < div slot="footer" class="dialog-footer"> < a-button @click="handleClose" type="primary">关 闭</ a-button > </ div > </ a-modal > </ template > < script > export default { name: "iHotelConfirm", data() { return { }; }, methods:{ handleClose(){ this.dialogVisible = false } } }; </ script > < style lang="less" scoped> .confirm-title{ color: #323233; font-weight: 500; font-size: 16px; line-height: 1.4; img{ width: 16px; height: 16px; margin-right: 5px; } } .confirm-context{ margin-top: 8px; color: #323233; font-size: 14px; padding-left: 21px; } </ style > |
2. 在同等文件夹下面创建index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import Vue from 'vue' import confirm from './confirm.vue' // const iHotelConfirm = Vue.extend(require('./confirm.vue')) const iHotelConfirm = Vue.extend(confirm) function showConfirm (detail){ const _confirm = new iHotelConfirm({ data(){ return { message:detail.message, dialogVisible: true , } } }) const element = _confirm.$mount().$el document.body.appendChild(element) } showConfirm.install = Vue => { Vue.prototype.$iHotelConfirm = showConfirm // 将Notice组件暴露出去,并挂载在Vue的prototype上 } export default showConfirm |
3. 在main.js中引入
1 2 3 | //自定义tost iHotelConfirm import iHotelConfirm from './components/iHotelConfirm/index.js' Vue.use(iHotelConfirm) |
在代码中使用 this.$iHotelConfirm({message:"我是extend测试成功"})
展示效果:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具