likes
comments
collection
share

vue2封装一个确认框组件

作者站长头像
站长
· 阅读数 37

vue2封装一个确认框组件

所以我使用油猴插件实现了在本页面直接打开确认框发沸点的功能。

封装一个确认框组件

const ConfirmBox = {
  name: 'ConfirmBox',
  props: {
    title: {
      type: String,
      default: '提示',
    },
    content: String,
  },
  render(h) {
    const content = this.$slots.default || this.content;

    return h(
      'div',
      {
        staticClass: 'xx-confirm-box',
      },
      [
        h('div', { staticClass: 'xx-confirm-box-title' }, [
          h('div', { staticClass: 'title' }, this.title),
          h(
            'a',
            { staticClass: 'close', on: { click: this.handleClose } },
            '关闭'
          ),
        ]),
        h('div', { staticClass: 'xx-confirm-box-content' }, [content]),
        h('div', { staticClass: 'xx-confirm-box-footer' }, [
          h('button', { on: { click: this.handleClose } }, '取消'),
          h('button', { on: { click: this.handleConfirm } }, '确认'),
        ]),
      ]
    );
  },
  methods: {
    handleClose(e) {
      this.$emit('close', e);
    },
    handleConfirm(e) {
      this.$emit('confirm', e);
    },
  },
};

便捷使用方式封装

const ConfirmBoxConstructor = Vue.extend(ConfirmBox);

export const confirm = (options = {}) => {
  if (typeof options === 'string') options = { content: options };
  const { content, title, onConfirm, onClose } = options;
  let instance;
  const props = { content, title };
  const on = {};
  const close = () => instance.$destroy();
  on.close = onClose ? () => onClose(close) : close;
  on.confirm = onConfirm ? () => onConfirm(close) : close;

  if (typeof content === 'string') {
    instance = new ConfirmBoxConstructor({ propsData: props, on });
  } else {
    const CompConstructor = Vue.extend({
      render: h => h(ConfirmBox, { props, on }, [content]),
    });
    instance = new CompConstructor();
  }

  instance.$on('hook:mounted', () => {
    document.body.appendChild(instance.$el);
  });
  instance.$on('hook:destroyed', () => {
    instance.$el.remove();
  });

  instance.$mount();
};

使用方式

转载自:https://juejin.cn/post/7282603015750795301
评论
请登录