为了onepoint 项目的前端,我先学了一点 vue 和 bootstrap,后来也看了 bootstrap-vue 的 ui 组件库。项目中,需要一个全局的 confirm,prompt 方法,虽然 bootstrap-vue 本身自带有this.$bvModal.msgBoxConfirm(message, options) 方法,但是用起来感觉不太舒服,所以就自己动手写了一个。
大概原理就是利用 install 添加一个全局方法,利用 extend 创建一个 Vue 构造器,并用 vm.$mount 挂载。由于 install 只会执行一次,所以上述实例也只会创建一次,再利用 v-modal 控制组件的显示与隐藏,以此可以复用组件。
组件模板
//    src/components/confirm/main.vue
<template>
  <b-modal
    v-model="isShow"
    :centered="true"
    :title="title"
    :cancel-title="cancelTitle"
    :ok-title="okTitle"
    @ok="modalOk"
    @cancel="modalCancel"
    @close="modalClose"
  >
    <p class="my-4">{{message}}</p>
  </b-modal>
</template>
<script>
export default {
  data() {//这些属性放到props中也是可以的,由于我们的组件只创建一次,使用时只是修改这个实例的属性,放data中更简洁一些。
    return {
      isShow: false,
      message: "default message",
      title: "Confirm",
      cancelTitle: "取消",
      okTitle: "确定",
      ok: null,
      cancel: null,
      close: null
    };
  },
  methods: {
    modalOk() {
      if (this.ok) this.ok();
    },
    modalCancel() {
      if (this.cancel) this.cancel();
    },
    modalClose() {
      if (this.close) this.close();
    }
  }
};
</script>插件代码
//    src/components/confirm/index.js
import Confirm from './main.vue'
const defaultC = {
  isShow: true,
  message: "default message",
  title: "Confirm",
  cancelTitle: "取消",
  okTitle: "确定",
  ok: null,
  cancel: null,
  close: null
};
export default {
  install(Vue) {
    const ConfirmConstructor = Vue.extend(Confirm);
    const instance = new ConfirmConstructor();
    instance.$mount()
    document.body.appendChild(instance.$el)
    Vue.prototype.$confirm = (options) => {
      Object.assign(instance, defaultC, options);
    }
  }
}全局注册
import Confirm from './components/confirm/index'
Vue.use(Confirm)使用方式
this.$confirm({
    title: "rm",
    message: "remove: " + tPath,
    ok: () => {
        _this.sendCmd(cmd, {
            path: tPath
        });
    }
});当然也可以封装成符合自己习惯的参数,看个人习惯吧。
显示效果

confirm 也是一样的原理,代码就不贴出来了。

参考链接
			本文由 ukuq 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: Mar 12, 2020 at 12:13 am		
 
				