当前位置:   article > 正文

Elementui,通过Dialog,实现全局动态confirm自定义弹窗,不需要各页面单独引入组件(可显示页面、html、代码高亮显示、普通文字)_element弹窗组件dialog

element弹窗组件dialog

 动态挂载组件 

  1. // obj={
  2. // class:'弹窗最外面的名称',
  3. // title:'弹窗标题',
  4. // components:'传入的组件,需要先使用 import test from './components/test.vue' 引入,然后传递 test(components和content只能有一个,并且components里面的关闭和取消按钮需要自己写)'
  5. // propsData:组件的传递的参数(components传入的组件哈)
  6. // content:'弹窗内容(可以文字、html,也可以展示代码需要`<div></div>`包裹)',
  7. // width:'弹窗宽度',
  8. // cancelText:'取消按钮的文案,没有传不显示按钮',
  9. // confirmText:'确定按钮的文案,没有传不显示按钮',
  10. // style:'content内容的基础样式',
  11. // showClose:'是否显示弹窗右上角的关闭按钮',
  12. // twiceTitle:'确定时的二次确认文字,不传不会二次确定'
  13. // }
  14. Vue.prototype.$confirmDialog = async function(obj = null) {
  15. if (!obj) return
  16. const idName = 'confirmDialog_new_custom_' + new Date().getTime() + '_' + parseInt(Math.random() * 1000)
  17. const confirmDialog = (await import('@/components/dialog/confirmDialog.vue')).default
  18. const ConfirmDialogCom = Vue.component('confirmDialog', confirmDialog)// 创建组件
  19. // 给当前组件挂载父级页面的参数(即 main.js里面new Vue() 挂载的额外参数),这样内部的组件可以直接使用this.$router和this.$store,否则需要单独引入
  20. const componentsArray = ['store', 'router']
  21. const componentsObject = {
  22. root: this.$root,
  23. parent: this
  24. }
  25. componentsArray.forEach((item, index) => {
  26. if (Object.keys(this.$root.$options).indexOf(item) != -1) {
  27. componentsObject[item] = this[`$${item}`] || null
  28. } else {
  29. componentsArray[index] = null
  30. }
  31. })
  32. // 这里主要是给confirmDialog.vue组件挂载'store', 'router','root','parent',这几个参数,并加载到组件上去,parent就是当前页面的实例
  33. const confirmDialogComNew = new ConfirmDialogCom(componentsObject)// 创建组件实例(可以传递参数 { propsData: props })
  34. // 将需要重新挂载的参数传到组件(这里传入components时,为了让confirmDialog.vue组件内部再动态添加组件时需要和上面一样挂载的)
  35. confirmDialogComNew.componentsArray = [...['root', 'parent'], ...componentsArray].filter(n => n != null)
  36. const DOM = document.createElement('div')
  37. DOM.setAttribute('class', 'confirmDialog_new_custom')
  38. DOM.setAttribute('id', idName)
  39. document.body.appendChild(DOM)
  40. const comp = confirmDialogComNew.$mount(DOM.appendChild(document.createElement('template')))// 将虚拟dom节点改变成真实dom,获取组件的dom节点,并实现挂载
  41. comp.$watch('centerDialogVisible', (value) => { // 监听组件是否不显示,并删除组件、销毁组件
  42. if (!value) {
  43. document.body.removeChild(document.getElementById(idName))
  44. comp.$destroy()
  45. }
  46. }, { deep: true })
  47. return comp.showDialog(obj)
  48. }

confirmDialog.vue组件内容

  1. <template>
  2. <div :class="[className]">
  3. <el-dialog
  4. :title="title"
  5. :visible.sync="centerDialogVisible"
  6. :width="width"
  7. class="tishiDialog"
  8. :modal-append-to-body="false"
  9. :show-close="showClose"
  10. :close-on-click-modal="closeOnClickModal"
  11. :close-on-press-escape="closeOnPressEscape"
  12. center
  13. >
  14. <template v-if="componentName">
  15. <template v-if="propsData">
  16. <div ref="componentCustom" />
  17. </template>
  18. <template v-else>
  19. <component :is="componentName" ref="componentCustom" @close="close($event)"/>
  20. </template>
  21. </template>
  22. <template v-else>
  23. <div :style="contentStyle" :class="[$checkHtml(content)?'':'dialogContent']" v-html="content" />
  24. </template>
  25. <span slot="footer" class="dialog-footer">
  26. <el-button v-if="cancelText!=''" class="close_btn" @click="closeFn(1)">{{ cancelText }}</el-button>
  27. <el-button v-if="confirmText!=''" class="saves_btn" type="primary" @click="closeFn(2)">{{ confirmText }}</el-button>
  28. </span>
  29. </el-dialog>
  30. </div>
  31. </template>
  32. <script>
  33. export default {
  34. data() {
  35. return {
  36. dialogFn: null, // 回调方法
  37. content: '', // 内容,可以是html
  38. title: '', // 标题
  39. width: '500px', // 宽度
  40. centerDialogVisible: false,
  41. cancelText: '', // 取消按钮文字,不传不显示取消按钮
  42. confirmText: '', // 确定按钮文字,不传不显示确定按钮
  43. contentStyle: { 'text-align': 'center' }, // 内容的基础样式
  44. showClose: false, // 是否显示关闭按钮
  45. btnClickType: 0,//点击按钮的判断,1:取消,2:确定,0:其他
  46. closeOnClickModal: false, // 是否可以通过点击 modal 关闭 Dialog
  47. closeOnPressEscape: false, // 是否可以通过按下 ESC 关闭 Dialog
  48. twiceTitle: '', // 确定关闭时的二次确定文字,不传不会二次提示
  49. className: ''//弹窗的close,
  50. componentName: null,
  51. propsData: null,//组件的参数
  52. componentCustomDom: null
  53. }
  54. },
  55. watch: {
  56. centerDialogVisible(value) {
  57. if (!value) {
  58. if (this.componentCustomDom) {
  59. this.componentCustomDom.$destroy()
  60. }
  61. if (this.btnClickType == 0) {
  62. this.dialogFn({ close: true })
  63. }
  64. }
  65. }
  66. },
  67. methods: {
  68. // 判断是否存在html
  69. checkHtml(htmlStr){
  70. var reg = /<[^>]+>/g
  71. return reg.test(htmlStr)
  72. },
  73. // 关闭按钮的操作,主要是二次确定需要的
  74. hideFn(cancel, type) {
  75. if (cancel) {
  76. this.closed = true
  77. this.centerDialogVisible = false
  78. this.btnClickType = type
  79. if (type == 1) {
  80. this.dialogFn({ cancel: true })
  81. } else if (type == 2) {
  82. this.dialogFn({ confirm: true })
  83. } else {
  84. console.log('close')
  85. }
  86. }
  87. },
  88. // 关闭弹窗
  89. closeFn(type) {
  90. if (this.twiceTitle != '' && type == 2) {
  91. this.$confirm(this.twiceTitle)
  92. .then(_ => {
  93. this.hideFn(true, type)
  94. })
  95. .catch(_ => {})
  96. } else {
  97. this.centerDialogVisible = false
  98. this.btnClickType = type
  99. if (type == 1) {
  100. this.dialogFn({ cancel: true })
  101. } else {
  102. this.dialogFn({ confirm: true })
  103. }
  104. }
  105. },
  106. close(type = 'confirm') {
  107. if (type == 'confirm') {
  108. this.closeFn(2)
  109. } else {
  110. this.closeFn(1)
  111. }
  112. },
  113. showDialog(obj) {
  114. Object.assign(this.$data, this.$options.data.call(this))
  115. if (obj.class) this.className = obj.class
  116. if (obj.title) this.title = obj.title
  117. if (obj.content) this.content = this.formatHtml(obj.content)
  118. if (obj.width) this.width = obj.width
  119. if (obj.cancelText) this.cancelText = obj.cancelText
  120. if (obj.confirmText) this.confirmText = obj.confirmText
  121. if (obj.style) this.contentStyle = obj.style
  122. if (obj.showClose) this.showClose = obj.showClose
  123. if (obj.twiceTitle) this.twiceTitle = obj.twiceTitle
  124. if (obj.closeOnClickModal) this.closeOnClickModal = obj.closeOnClickModal
  125. if (obj.closeOnPressEscape) this.closeOnPressEscape = obj.closeOnPressEscape
  126. if (obj.propsData) this.propsData = obj.propsData
  127. if (this.cancelText == '' && this.confirmText == '' && !obj.components) this.showClose = true
  128. this.centerDialogVisible = true
  129. this.dialogFn = obj.success || (() => {})
  130. // 挂载组件
  131. if (obj.components) {
  132. if (obj.propsData) {
  133. const ConfirmDialogCom = Vue.component('ConfirmSolt', obj.components)// 创建组件
  134. const componentsObject = {}
  135. // 这样内部的组件可以直接使用this.$router、this.$store、this.$parent及this.$root,否则需要单独引入(获取传入的componentsArray,然后再次挂载到ConfirmSolt组件上)
  136. // ConfirmSolt组件的parent就是当前组件的this,其他的就直接区当前组件实例上的
  137. this.componentsArray.forEach(item => {
  138. componentsObject[item] = item == 'parent' ? this : this[`$${item}`]
  139. })
  140. // propsData 是组件传参
  141. const confirmDialogComNew = new ConfirmDialogCom(Object.assign(componentsObject, { propsData: obj.propsData ? obj.propsData : {}}))// 创建组件实例(可以传递参数 { propsData: props })
  142. confirmDialogComNew.$on('close', res => {
  143. this.close(res)
  144. })
  145. this.componentName = 'ConfirmSolt'
  146. this.$nextTick(() => {
  147. const comp = confirmDialogComNew.$mount(this.$refs.componentCustom)
  148. this.componentCustomDom = comp
  149. })
  150. } else {
  151. Vue.component('ConfirmSolt', obj.components)
  152. this.componentName = 'ConfirmSolt'
  153. this.$nextTick(() => {
  154. this.componentCustomDom = this.$refs.componentCustom
  155. })
  156. }
  157. }
  158. },
  159. // 实现可以显示html标签
  160. // this.content='`<div>测试显示div</div>`正常的文字'
  161. formatHtml(val) {
  162. const sing = '`'
  163. const regxd = RegExp(`${sing}<[^${sing}]+>${sing}`, 'g')
  164. val = val.replace(regxd, function(word) {
  165. if (/<[^<]+>/g.test(val)) { // 判断是否存在html标签
  166. const getHtml = (word) => {
  167. let wordString = word.replace(/^(\s|`)+|(\s|`)+$/g, '')// 清除前后`符号
  168. const htmlArray = []
  169. wordString.replace(/<\/[^<]+>/g, function(word1) { // 获取每个标签类型的结束标签,即存在/的标签,比如:</div>
  170. htmlArray.push(word1.replace(/^(\s|<\/)+|(\s|>)+$/g, ''))// 获取html里面存在的标签,并清除前<,后>
  171. })
  172. // 获取html标签以及中间的值
  173. const htmlText = []
  174. htmlArray.forEach(item => {
  175. const regX = RegExp(`<${item}[^<]+<\/${item}>`, 'g')
  176. console.log(regX)
  177. wordString.replace(regX, function(word2) {
  178. htmlText.push(word2)
  179. })
  180. })
  181. console.log(htmlText)
  182. htmlText.forEach(item => {
  183. var ele = document.createElement('span')
  184. ele.appendChild(document.createTextNode(item))
  185. wordString = wordString.replace(RegExp(item, 'g'), `<span class='codeHtml' style='display: inline-block;padding: 4px 2px;background-color: #fff5f5;color: #ff502c;border-radius: 2px;'>${ele.innerHTML}</span>`)
  186. })
  187. return wordString
  188. }
  189. return getHtml(word)
  190. } else {
  191. return word
  192. }
  193. })
  194. return val
  195. }
  196. }
  197. }
  198. </script>
  199. <style lang="scss" scoped>
  200. .dialogContent{
  201. line-height: 2;
  202. }
  203. ::v-deep .el-dialog{
  204. margin-top:0 !important ;
  205. top: 50%;
  206. transform: translateY(-50%);
  207. .el-dialog__header {
  208. width: 100%;
  209. height: 50px;
  210. line-height: 50px;
  211. position: relative;
  212. background-color: #d90e19;
  213. padding: 0;
  214. .el-dialog__headerbtn{
  215. top: 50%;
  216. margin-top: -10px;
  217. }
  218. .el-dialog__title {
  219. color: #fff;
  220. font-size: 16px;
  221. font-family: "PingFang";
  222. font-weight: 500;
  223. }
  224. .el-dialog__close {
  225. color: #fff;
  226. }
  227. }
  228. .el-dialog__body {
  229. padding-bottom: 10px;
  230. }
  231. .el-button{
  232. margin-left: 0 !important;
  233. margin-top: 10px;
  234. }
  235. .dialog-footer{
  236. display: flex;
  237. flex-wrap: wrap;
  238. justify-content: space-around;
  239. }
  240. .close_btn {
  241. width: 170px;
  242. color: #d90e19;
  243. border: 1px solid #d90e19;
  244. background-color: #fff;
  245. &:hover{
  246. background-color: rgba(217, 14, 25,0.1);
  247. border-color:rgba(217, 14, 25,0.1) ;
  248. color: #d90e19;
  249. }
  250. }
  251. .saves_btn {
  252. width: 170px;
  253. color: #fff;
  254. background-color: #d90e19;
  255. border-color:#d90e19 ;
  256. margin-left: 20px;
  257. &:hover{
  258. background-color: #c0121b;
  259. }
  260. }
  261. }
  262. </style>

使用: 

  1. this.$confirmDialog({
  2. title: '提示',
  3. content: '《长恨歌》是唐代诗人白居易创作的一首长篇叙事诗。此诗可分为三大段,从“汉皇重色思倾国”至“惊破霓裳羽衣曲”共三十二句为第一段,写唐玄宗和杨贵妃的爱情生活、爱情效果,以及由此导致的荒政乱国和安史之乱的爆发。从“九重城阙烟尘生”至“魂魄不曾来入梦”共四十二句为第二段,写马嵬驿兵变,杨贵妃被杀,以及此后唐玄宗对杨贵妃朝思暮想,深情不移。从“临邛道士鸿都客”至“此恨绵绵无绝期”共四十六句为第三段,写唐玄宗派人上天入地到处寻找杨贵妃和杨贵妃在蓬莱宫会见唐玄宗使者的情形',
  4. cancelText: '取消',
  5. confirmText: '确定',
  6. showClose:true,
  7. success: (res) => {
  8. console.log(res) //点击确定取消的返回值
  9. }
  10. })

1.如果传入显示的html,需要在弹窗传入一个class 

  1. this.$confirmDialog({
  2. class: 'testDialog',//传入class
  3. title: '提示',
  4. content: '<div class="nameTitle">测试的文字</div>',
  5. cancelText: '取消',
  6. confirmText: '确定',
  7. showClose:true,
  8. success: (res) => {
  9. console.log(res) //点击确定取消的返回值
  10. }
  11. })

 最后在页面新增一个没有scoped的进行写样式,就可以实现自定义显示样式了

  1. <style lang="scss">
  2. .tishiDialog{
  3. .nameTitle{
  4. color:red
  5. }
  6. }
  7. </style>

2. 弹窗需要显示html代码,需要使用``包裹

  1. this.$confirmDialog({
  2. title:'提示',
  3. content:'`<div style="background: red;">红色背景的div</div>`首先,我们来说一下怎么实现背景色时红色的,比如这个div,要自己尝试哈!!!`<span>测试span标签的</span>`',
  4. cancelText: '取消',
  5. confirmText: '确定',
  6. success: (res) => {
  7. console.log(res)
  8. }
  9. })

 

3.如果components传入一个页面 

  1. async fn(){
  2. this.$confirmDialog({
  3. title: '测试的',
  4. components: (await import('./components/test.vue')).default,
  5. width: '400px',
  6. success: (res) => {
  7. console.log(res)
  8. }
  9. })
  10. }

test.vue:

  1. <template>
  2. <div>
  3. <div>测试文字的</div>
  4. <span slot="footer" class="dialog-footer">
  5. <el-button class="cancelBtn" @click="closeFn(1)">取消</el-button>
  6. <el-button class="confirmBtn" type="primary" @click="closeFn(2)">确定</el-button>
  7. </span>
  8. </div>
  9. </template>
  10. <script>
  11. export default {
  12. data() {
  13. return {
  14. }
  15. },
  16. methods: {
  17. // 关闭
  18. closeFn(type) {
  19. if (type == 1) {
  20. this.$parent.close('cancel')
  21. //this.$emit('close','cancel')
  22. } else {
  23. // 这里时可以在组件里面调出二次确定的方法,主要使用的还是‘el-dialog’自带的‘$confirm’
  24. // this.$parent.$confirm('确定同意?').then((res) => {
  25. // if (res == 'confirm') {
  26. // console.log('同意了哈')
  27. // this.$parent.close('confirm')
  28. // }
  29. // }).catch((error) => {
  30. // if (error == 'cancel') {
  31. // console.log('没有同意哈')
  32. // }
  33. // })
  34. this.$parent.close('confirm')
  35. //this.$emit('close','confirm')
  36. }
  37. }
  38. }
  39. }
  40. </script>

 

 关闭弹窗需要使用    this.$parent.close( )  方法

 如果:

        要使用 this.$parent.close,需要 给当前组件挂载父级页面的参数 ,上面代码有说明。

不然:

        在内部页面使用router、store,需要单独 router,store使用需要单独引入,同时this.$parent无法使用,需要调用this.$emit('close','') 关闭

 Elementui预览图片,无需单独引入组件:

  1. // 预览大图
  2. // url:展示的图片
  3. // list:展示的所有图片数组
  4. Vue.prototype.$lookImageViewer: async function(url, list) {
  5. let listImg = list
  6. const thisIndex = list.indexOf(url)
  7. const firstArray = list.slice(thisIndex, list.length)
  8. const twoArray = list.slice(0, thisIndex)
  9. listImg = [...firstArray, ...twoArray]
  10. // this.$viewerApi({ images: listImg })//v-viewer组件
  11. const id = 'MyElImageViewer_' + new Date().getTime() + '_' + parseInt(Math.random() * 1000)
  12. // 引用组件(找到Elementui中image-viewer的位置)
  13. const ElImageViewer = (await import('element-ui/packages/image/src/image-viewer')).default
  14. const MyElImageViewer = Vue.component('MyElImageViewer', ElImageViewer)
  15. const MyElImageViewerNew = new MyElImageViewer({ propsData: {
  16. urlList: listImg,
  17. onClose: () => {
  18. // 删除组件
  19. compDOm.$destroy()
  20. document.body.removeChild(document.getElementById(id))
  21. }
  22. }})
  23. const DOM = document.createElement('div')
  24. DOM.setAttribute('id', id)
  25. DOM.setAttribute('class', 'imageSwipeViewer_Show')
  26. document.body.appendChild(DOM)
  27. // 挂载组件
  28. const compDOm = MyElImageViewerNew.$mount(DOM.appendChild(document.createElement('template')))
  29. compDOm.$nextTick(() => {
  30. const showDom = document.getElementById(id)
  31. showDom.querySelector('.el-icon-circle-close').style = 'font-size:38px;color:#fff'
  32. })
  33. }

使用: 

this.$lookImageViewer('https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF',['https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF'])

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/550097
推荐阅读
相关标签
  

闽ICP备14008679号