• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Vue 实现一个命令式弹窗组件功能

vue 搞代码 4年前 (2022-01-08) 22次浏览 已收录 0个评论

这篇文章主要介绍了vue实现命令式弹窗组件功能,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下

前言

在日常工作中弹窗组件是很常用的组件,但用得多还是别人的,空闲时间就自己来简单实现一个弹窗组件

涉及知识点:extend、$mount、$el

使用方式:

 this.$Confirm({ title:'自定义标题' }).then(res=>{ console.log(res) })

目录结构

index.vue:组件布局、样式、交互逻辑

index.js:挂载组件、暴露方法

知识点

在此之前,了解下涉及的知识点

1. extend

 使用这个api,可以将引入的vue组件变成vue构造函数,实例化后方便进行扩展

2. $mount

我们希望弹窗组件是在使用时才显示出来,那么就需要动态的向body中添加元素。使用$mount方法可以手动挂载一个vue实例,和 extend 刚好搭配使用,这个也是弹窗组件命令式的关键。

3. $el

 既然要添加dom元素,通过实例的$el属性,正好可以取到dom元素,之后就是使用原生方法进行添加节点啦~

代码实现

index.vue

  <div class="wrap"> <div class="main"> <div class="content"> {{title}} </div><div class="btn-grounp"> <div class="btn cancel">{{cancelText}}</div><div class="btn confirm">{{confirmText}}</div></div></div></div>
 
  .wrap{ position: fixed; top: 0; bottom:0; left:0; right:0; display:flex; justify-content: center; align-items: center; background: rgba(0,0,0,.3); } .main{ width: 30%; padding: 10px; background: #fff; box-shadow: 0 0 10px 1px #ddd; border-radius: 5px; } .content{ color:#424242; font-size: 20px; } .btn-grounp{ margin-top: 15px; display:flex; justify-content: flex-end; } .btn{ margin-left: 15px; padding: 5px 20px; border-radius: 5px; font-size: 16px; color:#fff; } .confirm{ background: lightblue; } .cancel{ background: lightcoral; } 

index.js

 import Vue from 'vue' import comfirm from './index.vue' let newInstance = null //将vue组件变为构造函数 let ConfirmConstructor = Vue.extend(comfirm) let init = (options)=>{ //实例化组件 newInstance = new ConfirmConstructor() //合并配置选项 Object.assign(newInstance,options) //加载dom document.body.appendChild(newInstance.$el) } let caller = (options)=>{ //options 为调用组件方法时传入的配置选项 if(!newInstance){ init(options) } return newInstance.show(vm =>{newInstance = null}) } export default { install(vue){ vue.prototype.$Confirm = caller } }

main.js

上面我对外暴露的对象中含有install方法,这里可以使用Vue.use注册组件(使用Vue.use后,会查找install方法进行调用),将组件调用方法挂载到Vue原型上。

 import Confirm from './components/confirm' Vue.use(Confirm)

写在最后

这个弹窗组件比较简陋,还有很多地方可以完善,等有时间再搞了~

本文来源gaodaima#com搞(代@码$网6总结

以上所述是小编给大家介绍的Vue 实现一个命令式弹窗组件功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对gaodaima搞代码网网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

以上就是Vue 实现一个命令式弹窗组件功能的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Vue 实现一个命令式弹窗组件功能

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址