Skip to content

Vue自定义模态框 #95

@TieMuZhen

Description

@TieMuZhen

模框组件

// MyModal.vue
<template>
  <div class="dialog">
    <slot name="content"></slot>
    <div class="btn-group">
      <div class="btn" @click="cancel">{{ modal.cancelButtonText }}</div>
      <div class="btn" @click="submit">{{ modal.confirmButtonText }}</div>
    </div>
  </div>
</template>

<script>
export default {
  name: "MyModal",
  props: {
    dialogOption: Object
  },
  data() {
    return {
      resolve: "",
      reject: "",
      promise: "" //保存promise对象
    };
  },
  computed: {
    modal() {
      let option = this.dialogOption;
      return {
        cancelButtonText: option.cancelButtonText
          ? option.cancelButtonText
          : "取消",
        confirmButtonText: option.confirmButtonText
          ? option.confirmButtonText
          : "确定"
      };
    }
  },
  methods: {
    //确定,将promise断定为完成态
    submit() {
      this.resolve();
    },
    // 取消,将promise断定为reject状态
    cancel() {
      this.reject();
    },
    //显示confirm弹出,并创建promise对象,给父组件调用
    cb() {
      this.promise = new Promise((resolve, reject) => {
        this.resolve = resolve;
        this.reject = reject;
      });
      return this.promise; //返回promise对象,给父级组件调用
    }
  }
};
</script>

父组件

// app.vue
<template>
  <div id="app">
    <button @click="open">打开模态框</button>
    <!-- 自定义模态框组件 -->
    <my-modal :dialogOption="dialogOption" v-show="isShow" ref="dialog">
      <div slot="content">
        <span>插入新内容</span>
      </div>
    </my-modal>
  </div>
</template>

<script>
import MyModal from "./components/MyModal.vue";
export default {
  name: "app",
  components: {
    MyModal
  },
  data() {
    return {
      isShow: false,
      dialogOption: {
        cancelButtonText: "取消",
        confirmButtonText: "确定"
      }
    };
  },
  methods: {
    open() {
      this.isShow = true;
      this.$refs.dialog
        .cb()
        .then(() => { // 传到MyModal中的回调函数
          this.isShow = false;
        })
        .catch(() => {  // 传到MyModal中的回调函数
          this.isShow = false;
        });
    }
  }
};
</script>

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions