首頁  >  文章  >  web前端  >  如何使用v-model與promise兩種方式實作vue彈窗組件

如何使用v-model與promise兩種方式實作vue彈窗組件

php中世界最好的语言
php中世界最好的语言原創
2018-05-28 15:00:302036瀏覽

這次為大家帶來如何使用v-model與promise兩種方式實現vue彈窗組件,使用v-model與promise兩種方式實現vue彈窗組件的注意事項有哪些,下面就是實戰案例,一起來看一下。

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

一.概覽

先看最後的呼叫方式

props $emit方式

<chat-modal ref="chat-modal" v-model="showModal" cancelText="取消" sureText="确认" title="弹窗标题" small @on-ok="onOK" @on-cancel="onCancel">
  <p>slot的东西,想向弹窗中添加自定义的内容</p>
</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 => {
      //点击取消的回调
    })
  }
}

第二種方式的好處就是把所有的邏輯都集中到了一個方法裡。

二.看下元件的原始碼

tip:樣式有些爛...

<template>
  <p>
    <p class="shadow" v-show="showModal"></p>
    <p class="modal" :class="{&#39;smSize&#39;: otherText.small || small}" v-show="showModal">
      <p class="header">{{ otherText.title || title}}</p>
      <p class="body">
        <slot></slot>
      </p>
      <p class="footer">
        <p class="item success" id="sure" ref="sure" @click="makeSure" v-show="otherText.sureText || sureText">{{ otherText.sureText || sureText }}</p>
        <p class="item red" id="cancel" ref="cancel" @click="makeCancel" v-show="otherText.cancelText || cancelText">{{ otherText.cancelText || cancelText }}</p>
      </p>
    </p>
  </p>
</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來接的,這種方式透過在元件內部定義了另一個物件來接傳進來的值,

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了

this.$refs["sure"].addEventListener("click", () => {
  this.showModal = false;
  resolve("点击了确定");
});

取得確定按鈕的DOM元素綁定點擊事件,回調裡將showModal置為false並且resolve,

this.$refs["cancel"].addEventListener("click", () => {
  this.showModal = false;
  reject("点击了取消");
});

取得取消按鈕的DOM綁定點擊事件,回調裡reject.

遇到的坑

#這之前遇到了一個坑,因為第一次已經綁定了點擊事件,第二次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();

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

如何使用Vue内父子组件通讯todolist组件

如何使用Vue整合AdminLTE模板

以上是如何使用v-model與promise兩種方式實作vue彈窗組件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn