elementUI的对话框

图一

img


图二

img


图三

img


在上图中每次点击查看或者设置按钮时,都会弹出对话框,可是这么多对话框,我不能每个按钮都写一个dialog,在创建多个form来绑定,对于多个对话框,我想只写一个dialog,实现思路是什么

dialog用一个,动态来设置dialog属性,显示不同组件

<el-dialog
  :title="dialogProps.title"
  :visible.sync="dialogProps.visible"
  :width="dialogProps.width">
  <component :is='dialogCpt'></component>
</el-dialog>


dialogProps: {
  title: '',
  visible: false,
  width: '600px'
},
dialogCpt: '',

可以使用一个全局的 dialog,然后在点击“设置”或“查看”按钮时,动态地设置 dialog 的标题、内容、确认按钮和取消按钮的回调函数,从而实现多个对话框的复用。

参考以下案例:
1.在 Vue 的全局实例中添加一个 dialog,可以放在 main.js 中:

import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

import App from './App.vue'

Vue.use(ElementUI)

// 在 Vue 的全局实例中添加一个 dialog
Vue.prototype.$dialog = {
  title: '',
  content: '',
  confirm: null,
  cancel: null,
  visible: false
}

new Vue({
  render: h => h(App),
}).$mount('#app')

2.在组件中绑定点击事件,设置 dialog 的标题、内容、确认按钮和取消按钮的回调函数,最后将 dialog 显示出来:

<template>
  <div>
    <el-table :data="tableData">
      <el-table-column prop="column1"></el-table-column>
      <el-table-column prop="column2"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="handleView(scope.row)">查看</el-button>
          <el-button @click="handleSet(scope.row)">设置</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="$dialog.title" :visible.sync="$dialog.visible" :before-close="handleCancel">
      <div v-html="$dialog.content"></div>
      <span slot="footer">
        <el-button @click="handleConfirm">确定</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: []
    }
  },
  methods: {
    handleView(row) {
      this.$dialog.title = '查看'
      this.$dialog.content = `<p>${row.column2}</p>`
      this.$dialog.confirm = null
      this.$dialog.cancel = null
      this.$dialog.visible = true
    },
    handleSet(row) {
      this.$dialog.title = '设置'
      this.$dialog.content = `<input type="text" v-model="form.field1">`
      this.$dialog.confirm = this.handleConfirmSet
      this.$dialog.cancel = null
      this.$dialog.visible = true
    },
    handleConfirmSet() {
      console.log(this.form.field1)
      // do something
    },
    handleConfirm() {
      if (this.$dialog.confirm) {
        this.$dialog.confirm()
      } else {
        this.$dialog.visible = false
      }
    },
    handleCancel() {
      if (this.$dialog.cancel) {
        this.$dialog.cancel()
      } else {
        this.$dialog.visible = false
      }
    }
  }
}
</script>

3.在 dialog 的确认和取消按钮的回调函数中,根据需要执行相应的操作。其中,在设置对话框的确认按钮的回调函数中,需要在组件的 data 中定义一个 form 对象,用于绑定输入框的值。