纯js文件调用element-ui Dialog

3,030 阅读1分钟

背景:项目中前后端使用 websocket 进行通信,后端一有消息,就会将消息主动推送给前端,前端在全局进行弹窗展示。我的想法是在 main.js 里注册一个 js 方法,当前端接收到消息后,就会弹窗提醒。如果弹窗是简单的交互,几行文字,那就用 element-ui 的 messageBox 就好,但我们要求显示的内容很多,稍显复杂,则考虑使用 dialog。

解决办法:

1.先写好 dialog 的组件

// dialog.vue

<template> 
 <div>    
    <el-dialog      
     :title="title"      
     :visible.sync="dialogVisible"      
     width="30%"      
     :append-to-body="true
    ">      
        <span>{{ message }}</span>      
        <span slot="footer" class="dialog-footer">        
         <el-button @click="onCancel">取 消</el-button>        
         <el-button type="primary" @click="onSubmit">确 定</el-button>      
        </span>    
    </el-dialog>  
  </div>   
</template>

// js 部分

methods: {      
    open(title, message, cbs = {} ) {
        this.title = title
        this.message = message
        this.dialogVisible = true
        this.cbs = cbs
        this.isOpenFlag = true
      },
      onSubmit() {
        if (Object.prototype.toString.call(this.cbs['onSubmit']) === '[object Function]') {
          this.cbs['onSubmit']()
        }
      },
      onCancel() {
        if (Object.prototype.toString.call(this.cbs['onCancel']) === '[object Function]') {
          this.cbs['onCancel']()
        }
      }
    }

2.触发 dialog 打开

// dialogHandler.js

import Dialog from './dialog'
import Vue from 'vue'
let $vm, dialogConstructor;

export function openDialog(title, message, cbs) {
  if (!dialogConstructor) {
    dialogConstructor = Vue.extend(Dialog)
  }  if (!$vm) {
    $vm = new dialogConstructor()
  }
  $vm.$mount().open(title, message, cbs)
}

// 两个 if 判断,是为了有新的消息时,不再重复弹出新的 dialog

3.纯 js 文件中,开启弹窗

// xxx.js

import { openDialog } from "./dialogHandler"

openDialog('测试', '消息示例', {
            onSubmit(){console.log('点了确定按钮')},
            onCancel(){console.log('点了取消按钮')}
          })

ok ~ 亲测有效!

参考链接:

弹框支持函数直接调用

Vue.extend创建实例

Vue封装插件