兩種方式lu一個vue彈窗組件(v-model與promise方式)

最近公司有一個後臺業務雖然也是寫在了現有的後臺系統中,可是以後要爲這個業務單獨拉出來新建一個後臺系統,因此現有的後臺系統中的vue組件庫,就不能用了(由於不知道未來的系統要基於什麼組件庫,以防給將來移植項目帶來麻煩),此次業務中又遇到了彈窗的功能,因此只能手動寫一個了(雖說彈窗組件很簡單,也是想本身總結一下,有不對的地方也請指出),一開始用傳統的props,$emit可是以爲要接兩個取消與確認的回調這塊的邏輯分散了因此就用了promise兩個回調的方式把兩個回調寫在了一塊兒,並不必定好,算是提供一種思路吧。css

一.概覽

先看最後的調用方式vue

props $emit方式
<chat-modal ref="chat-modal" v-model="showModal" cancelText="取消" sureText="確認" title="彈窗標題" small @on-ok="onOK" @on-cancel="onCancel">
    <div>slot的東西,想向彈窗中添加自定義的內容</div>
</chat-modal>

methods: {
    display() {
      this.showModal = true;//交互點擊手動觸發顯示彈窗  
    },
    onOK() {},//點擊確認的回調
    onCancel() {}//點擊取消的回調
}

promise的回調方式
<chat-modal ref="chat-modal"></chat-modal>

methods: {
    display() {
        this.$refs["chat-modal"].openModal({
            title: "彈窗標題",
            sureText: "確認",
            cancelText: "取消"
        }).then(res => {
            //點擊確認的回調
        }, res => {
            //點擊取消的回調
        })
    }
}
複製代碼

第二種方式的好處就是把全部的邏輯都集中到了一個方法裏。promise

二.看下組件的源碼

tip: 樣式有些爛...bash

<template>
    <div>
        <div class="shadow" v-show="showModal"></div>
        <div class="modal" :class="{'smSize': otherText.small || small}" v-show="showModal">
            <div class="header">{{ otherText.title || title}}</div>
            <div class="body">
                <slot></slot>
            </div>
            <div class="footer">
                <div class="item success" id="sure" ref="sure" @click="makeSure" v-show="otherText.sureText || sureText">{{ otherText.sureText || sureText }}</div>
                <div class="item red" id="cancel" ref="cancel" @click="makeCancel" v-show="otherText.cancelText || cancelText">{{ otherText.cancelText || cancelText }}</div>
            </div>
        </div>
    </div>
</template>

<script>
//此組件提供兩種調用方法,能夠在組件上v-model一個表示是否顯示彈窗的對話框,而後須要的一些值經過props傳入,而後$emit在組件上@監聽作回調
//第二中方法全部的傳值回調都只須要在組件內部的一個方法調用而後在組件外部this.$refs[xxx].open調用而後.then觸發回調,比上一種方便些
var initOtherText = {
    sureText: "",
    cancelText: "",
    title: "",
    small: false
};

export default {
    props: {
        title: {
            type: String
        },
        sureText: {
            type: String
        },
        cancelText: {
            type: String
        },
        value: {
            type: Boolean
        },
        small: {
            type: Boolean
        }
    },
    watch: {
        value(newVal) {
            this.showModal = newVal;
        }
    },
    data() {
        return {
            otherText: JSON.parse(JSON.stringify(initOtherText)),
            showModal: this.value
        };
    },
    methods: {
        makeSure() {
            this.$emit("on-ok");
            this.$emit("input", false);
        },
        makeCancel() {
            this.$emit("on-cancel");
            this.$emit("input", false);
        },
        openModal(otherText) {
            this.otherText = { ...otherText };
            this.showModal = true;
            var pms = new Promise((resolve, reject) => {
                this.$refs["sure"].addEventListener("click", () => {
                    this.showModal = false;
                    resolve("點擊了肯定");
                });
                this.$refs["cancel"].addEventListener("click", () => {
                    this.showModal = false;
                    reject("點擊了取消");
                });
            });
            return pms;
        }
    }
};
</script>

<style lang="scss" scoped>
.shadow {
    background-color: rgba(0, 0, 0, 0.5);
    display: table;
    height: 100%;
    left: 0;
    position: fixed;
    top: 0;
    transition: opacity 0.3s ease;
    width: 100%;
    z-index: 50;
}
.modal {
    display: table-cell;
    vertical-align: middle;
    overflow-x: hidden;
    position: fixed;
    background-color: white;
    box-shadow: rgba(0, 0, 0, 0.33) 0px 2px 8px;
    border-radius: 5px;
    outline: 0px;
    overflow: hidden;
    transition: all 0.3s ease;
    width: 600px;
    height: 400px;
    top: 50%;
    left: 50%;
    margin-top: -200px;
    margin-left: -300px;
}

.header {
    align-items: center;
    background-color: #62a39e;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.16);
    color: #fff;
    font-weight: bold;
    display: -ms-flexbox;
    display: flex;
    height: 3.5rem;
    padding: 0 1.5rem;
    position: relative;
    z-index: 1;
}

.body {
    align-items: center;
    padding: 1.5rem;
}

.footer {
    justify-content: flex-end;
    padding: 1.5rem;
    position: absolute;
    bottom: 0;
    width: 100%;
    float: right;
}

.item {
    color: white;
    text-align: center;
    border-radius: 5px;
    padding: 10px;
    cursor: pointer;
    display: inline-block;
}
.info {
    background-color: #2196f3;
}
.success {
    background-color: #62a39e;
}
.red {
    background-color: #e95358;
}

.smSize {
    height: 200px;
}
</style>
複製代碼

首先分析一下第一種方式: 調用者須要在組件外部v-model上綁定一個變量(例中爲showModal)來指示彈窗是否顯示,顯示的時候須要在組件外部手動設置this.showModal = true,組件內部props定義一個屬性來接這個值爲value: {type: Boolean},同時在組件內部在用聲明一個變量用來同步外部傳進來的props值默認值爲 showModal: this.value(內部聲明的值也叫了showModal),在watch中監聽進行同步 watch: { value(newVal) { this.showModal = newVal } };而後把組件內部的這個showModal值綁定在須要顯示或者隱藏的DOM元素上。向外拋出事件的時候是在點擊組件內部的肯定與關閉按鈕時候異步

makeSure() {
            this.$emit("on-ok");
            this.$emit("input", false);
        },
makeCancel() {
            this.$emit("on-cancel");
            this.$emit("input", false);
        }
複製代碼

this.$emit("on-ok");this.$emit("on-cancel"); 這兩句的是向外拋出事件在組件外部@接一下而後寫本身須要的回調函數。這時就能夠實現彈窗的顯示與隱藏了,你可能發現並無一句代碼去設置this.showModal = false;彈窗就隱藏了。主要是由於這幾句代碼 v-model = 'showModal'和 組件內部的 props: {value: {type: Boolean}} this.$emit("input", false) 。v-model實際上是vue的語法糖, <chat-modal v-model="showModal">其實能夠寫爲 <chat-modal :value="showModal" @input="showModal = arguments[0]">因此要求咱們在組件內部必須規定props的名字必須爲value, 而後在組件內部觸發肯定或者取消的時候在組件內部觸發this.$emit("input", false)這樣實現了直接隱藏彈窗而沒必要打擾用戶讓用戶在組件外部在手動將showModal置爲false.函數

而後來看promise的方式: 第一種方式傳進來的值都經過props來接的,這種方式經過在組件內部定義了另外一個對象來接傳進來的值,flex

var initOtherText = {
    sureText: "",
    cancelText: "",
    title: "",
    small: false
};
otherText: JSON.parse(JSON.stringify(initOtherText)),
複製代碼

而後在menthods裏定義了一個名爲openModal的方法,而後把傳進來的一系列參數賦值給組件內部的對象 this.otherText = { ...otherText }; this.showModal = true;而且將showModal置爲true,而後每次觸發的時候新建一個promise對象,裏面的異步事件爲點擊肯定和取消的兩個點擊事件,這裏要操做DOM了ui

this.$refs["sure"].addEventListener("click", () => {
    this.showModal = false;
    resolve("點擊了肯定");
});
複製代碼

獲取肯定按鈕的DOM元素綁定點擊事件,回調裏將showModal置爲false而且resolve,this

this.$refs["cancel"].addEventListener("click", () => {
    this.showModal = false;
    reject("點擊了取消");
});
複製代碼

獲取取消按鈕的DOM綁定點擊事件,回調裏reject.flexbox

遇到的坑

這以前遇到了一個坑,由於第一次已經綁定了點擊事件,第二次resolve和reject就會失敗,本想取消一下綁定事件,可是由於將整個彈窗v-show="showModal"的緣由整個DOM被display:none;了就不須要手動解綁了。 第二個是關於用v-if仍是v-show來隱藏彈窗,一開始用的是v-if可是發如今這步時

this.showModal = true;
var pms = new Promise((resolve, reject) => {
    this.$refs["sure"].addEventListener.xxx//省略
});
return pms;
複製代碼

將showModal置爲true時而後就去綁定事件這時候尚未DOM尚未解析玩DOM樹上尚未,要不就得用this.$nextTick增長了複雜度,最後採用了v-show;

關於優先級問題

若是既在組件上用prop傳了值(title,sureText之類的)如 <chat-modal" title="xx" sureText="xxx"></chat-modal> 也在方法裏傳了

this.$refs["chat-modal"].openModal({
    title: "服務小結",
    sureText: "提交併結束",
    cancelText: "取消"
    }).then();
複製代碼

是以方法的優先級爲高,在組件內部DOM元素上經過||設置了優先級,好比 <div class="header popModal">{{ otherText.title || title}}</div> 有方法的值取方法的值,沒有取props得值。

有很差或者不對的地方歡迎指正

相關文章
相關標籤/搜索