记一次使用Vue.extend封装的方法

381 阅读1分钟

方法:

import Vue from 'vue';

export default function create(component, props) {
  const Ctor = Vue.extend(component);
  const div = document.createElement('div');
  document.body.appendChild(div);
  const ctor = new Ctor({
    propsData: {
      ...props
    }
  }).$mount(div);

  ctor.remove = () => {
    ctor.$el.remove();
    ctor.$destroy();
  }
  return ctor;
}

消息提醒框:

<template>
  <div class="box" v-if="isShow">
    <h2>{{title}}</h2>
    <p class="box-content">{{message}}</p>
  </div>
</template>

<script>
export default {
  props: {
    title: {
      type: String,
      default: ""
    },
    message: {
      type: String,
      default: ""
    },
    duration: {
      type: Number,
      default: 1000
    }
  },
  data() {
    return {
      isShow: false
    };
  },
  methods: {
    show() {
      this.isShow = true;
      setTimeout(this.hide, this.duration);
    },
    hide() {
      this.isShow = false;
      this.remove();
    }
  }
};
</script>

<style>
.box {
  position: fixed;
  width: 100%;
  top: 16px;
  left: 0;
  text-align: center;
  pointer-events: none;
  background-color: #fff;
  border: grey 3px solid;
  box-sizing: border-box;
}
.box-content {
  width: 200px;
  margin: 10px auto;
  font-size: 14px;  
  padding: 8px 16px;
  background: #fff;
  border-radius: 3px;
  margin-bottom: 8px;
}
</style>

调用:

create(Notice, {
  title: '消息提示',
  message: '错误'
}).show()