<template>
  <div class='modal' v-if='visible'>
    <div class='modal-dialog'>
      <div class='modal-content'>
        <div class='modal-header'>
          <h5 class='modal-title'>{{ title }}</h5>
          <button type='button' class='close' @click='closeModal'>
            <span aria-hidden='true'>&times;</span>
          </button>
        </div>
        <div class='modal-body'>
          <slot></slot>
        </div>
        <div class='modal-footer'>
          <button type='button' class='btn btn-secondary' @click='closeModal'>
            {{ cancelText }}
          </button>
          <button type='button' class='btn btn-primary' @click='confirm'>
            {{ confirmText }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: 'Modal',
  props: {
    title: {
      type: String,
      default: '提示',
    },
    visible: {
      type: Boolean,
      default: false,
    },
    confirmText: {
      type: String,
      default: '确定',
    },
    cancelText: {
      type: String,
      default: '取消',
    },
  },
  methods: {
    closeModal() {
      this.$emit('update:visible', false);
    },
    confirm() {
      this.$emit('confirm');
    },
  },
};
</script>
<p>该组件接受以下 props:</p>
<ul>
<li><code>title</code>:弹框标题,默认为'提示'。</li>
<li><code>visible</code>:控制弹框是否显示,默认为<code>false</code>。</li>
<li><code>confirmText</code>:确定按钮文本,默认为'确定'。</li>
<li><code>cancelText</code>:取消按钮文本,默认为'取消'。</li>
</ul>
<p>该组件包含一个插槽,可以在弹框中渲染任意内容。它还触发两个事件:</p>
<ul>
<li><code>update:visible</code>:当用户关闭弹框时,该事件会触发,将<code>visible</code>属性设置为<code>false</code>。</li>
<li><code>confirm</code>:当用户点击确定按钮时,该事件会触发。</li>
</ul>
<p>你可以像这样在父组件中使用它:</p>
<pre><code class="language-vue">&lt;template&gt;
  &lt;div&gt;
    &lt;button @click='showModal = true'&gt;打开弹框&lt;/button&gt;
    &lt;modal :visible.sync='showModal' @confirm='handleConfirm'&gt;
      &lt;p&gt;这里是弹框内容&lt;/p&gt;
    &lt;/modal&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
import Modal from './Modal.vue';

export default {
  name: 'App',
  components: {
    Modal,
  },
  data() {
    return {
      showModal: false,
    };
  },
  methods: {
    handleConfirm() {
      console.log('用户点击了确定按钮');
    },
  },
};
&lt;/script&gt;
</code></pre>
<p>在这个例子中,我们使用了一个<code>showModal</code>属性来控制弹框的显示。当用户点击'打开弹框'按钮时,我们将<code>showModal</code>设置为<code>true</code>,这将显示弹框。我们还使用了<code>.sync</code>修饰符将<code>visible</code>属性绑定到<code>showModal</code>,这意味着当用户关闭弹框时,<code>showModal</code>会自动更新为<code>false</code>,而不需要手动更新。</p>
<p>当用户点击'确定'按钮时,<code>handleConfirm</code>方法会被调用。你可以在这个方法中执行任何你想要的操作,比如向服务器发送请求或者更新页面内容。</p>
<p>这个弹框组件只是一个基础示例,你可以根据自己的需求进行扩展和定制。</p>
Vue 通用弹框组件封装:简洁易用,可扩展

原文地址: https://www.cveoy.top/t/topic/nPTg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录