对element-ui的el-dialog进行封装,应该怎样处理visible?

前端到处需要用到e-dialog,对dialog的样式,close处理,visible处理的重复性代码很多,打算对其进行进一步封装,写一个我自己的at-dialog,里头的slot留给el-dialog,然后在index.vue的子组件testAtDialog.vue里面使用这个at-dialog。相当于用了三层父子关系,这个visible怎么样处理才能管用?下面的代码没法把el-dialog显示出来:

index.vue:

        <!-- 测试代码 -->
        <test-at-dialog ref="testAtDialog" :visible='testDialogVisible' />

其中的testDialogVisible在index.vue的data中定义:
testDialogVisible: { bol: false },

testAtDialog.vue:

<template>
  <at-dialog ref="dialog" :visible="dialogVisible" :title="_('Test')" size="mini">
    <span>This is at dialog.</span>
  </at-dialog>
</template>
<script>
export default {
  name: 'testAtDialog',
  props: ['visible'],
  data() {
    return {
      dialogVisible: { bol: false },
    }
  },
  watch: {
    visible: {
      handler: function(val, oldval) {
        this.dialogVisible.bol = val
        if (val.bol) {
          this.init()
        }
      },
      deep: true,
      immediate: true
    },
  },

  methods: {
    init() {
      console.log('init')
    },
  }
}

</script>
<style lang="scss" scoped>
</style>

最后是封装了el-dialog的组件at-dialog:

<template>
  <el-dialog :title="title" :visible.sync="visible.bol" class='dialog_formStyle' :width="width">
    <slot></slot>
  </el-dialog>
</template>
<script>
export default {
  name: 'atDialog',

  props: {
    title: {
      type: String,
      default: this._("No Title"),
    },
    size: {
      type: String,
      default: "small"
    },
    visible: {
      type: Object,
      default: { bol: false }
    }
  },

  data() {
    return {
      width: "600px",
    };
  },

  watch: {
    visible() {
      console.log('watch visible', this.visible)
    },
    size() {
      switch (this.size) {
        case "auto":
          this.width = ""
          break;
        case "medium":
          this.width = "800px"
          break;
        case "small":
          this.width = "600px"
          break;
        case "mini":
          this.width = "400px"
          break;
      }
    },
  },

  methods: {
    closeDialog() {
      this.visible.bol = false
      // this.$emit('update:show', false)
    },
  }
};

</script>
阅读 11.6k
2 个回答

使用vue2.4新加的特性 $attrs $listeners

调用

<testDialog :visible.sync="visible" title="弹框二次封装"/>

封装

<template>
  <div>
    <el-dialog v-bind="$attrs" v-on="$listeners">
      弹窗内容
      <span slot="footer">
        <el-button @click="$emit('update:visible', false)">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<el-dialog :visible.sync="mVisible">
  props: {
    visible: {
      type: Boolean,
      default: false
    },
  },
  computed: {
    mVisible: {
      get() {
        return this.visible
      },
      set(s) {
        this.$emit('update:visible', s);
      }
    }
  }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题