vue 自定義插件編寫之 confirm

插件通常用來爲 Vue 添加全局功能

 

使用插件

通過 Vue 的全局方法 Vue.use() 使用,

當然,在使用這個方法之前,你的 Vue 實例 必須已經初始化完成

import myPlugin from './plugIn/myPlugin'

// 該方法,會調用 myPlugin 的 install 方法

Vue.use(myPlugin) 

開發插件 (寫一個 confirm 例子)

定義 confirm template

<template>
  <div id="confirm" :id="show?'show':'hidden'">
    <div class="confirm-content">
      <div class="head">{{config.title}}</div>
      <div class="body">確定執行這個操作嗎?</div>
      <div class="footer">
        <span class="cancle" @click="cancleBtnClick(false)">取消</span>
        <span class="sure" @click="sureBtnClick(true)">確定</span>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      show: false
    };
  },
  props: {
    config: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  methods: {}
};
</script>
<style scoped>
#confirm {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 9000;
}
#show {
  display: block;
}
#hidden {
  display: none;
}
.confirm-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%);
  background: white;
  width: 400px;
  height: 250px;
  border-radius: 10px;
}
.head {
  font-weight: bold;
  font-size: 22px;
  text-align: center;
  padding: 15px;
}
.body {
  font-size: 18px;
  padding: 15px;
}
.footer {
  display: flex;
  font-size: 16px;
  line-height: 30px;
  text-align: center;
  padding: 15px;
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
}
.footer span {
  cursor: pointer;
  flex: 1;
}
</style>

定義 Confirm.js


import ConfirmView from './Confirm.vue'

import Vue from 'vue'

let Confirm = {};

Confirm.install = function (Vue, options) {

    const ConfirmViewConstructor = Vue.extend(ConfirmView)

    // 生成一個該子類的實例
    const instance = new ConfirmViewConstructor();

    Vue.prototype.$lzyconfirm = (config)=>{

        // 這裏 return 一個 Promise 
        // 在項目中使用的時候,就可以進行鏈式調用了~
        return new Promise((resolve,reject)=>{

            instance.config = config;

            instance.show = true;

            instance.sureBtnClick = ()=>{

                instance.show = false;

                resolve(true)

            }

            instance.cancleBtnClick = ()=>{

                instance.show = false;

                resolve(false)

            }

        })

    }

    // 將這個實例掛載在我創建的div上
    // 並將此div加入全局掛載點內部
    instance.$mount(document.createElement('div'))

    document.body.appendChild(instance.$el)

}

export default Confirm;

目錄結構如下:

在main.js安裝


import Confirm from './plugIn/Confirm/Confirm.js'

Vue.use(Confirm)

在項目中使用

 this.$lzyconfirm({

     title:'這是什麼東西~',

     content:"我也不知道這是什麼東西啊!!!"

}).then(res=>{

     console.log(res)

})

效果如下:

分別點擊取消和確定的時候,上面的 console 會打印出來 false 和 true

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章