利用vue實現模態框組件_javascript技巧

來源:互聯網
上載者:User

基本上每個項目都需要用到模態框組件,由於在最近的項目中,alert組件和confirm是兩套完全不一樣的設計,所以我將他們分成了兩個組件,本文主要討論的是confirm組件的實現。

組件結構

<template>  <div class="modal" v-show="show" transition="fade">    <div class="modal-dialog">      <div class="modal-content">        <!--頭部-->        <div class="modal-header">          <slot name="header">            <p class="title">{{modal.title}}</p>          </slot>          <a v-touch:tap="close(0)" class="close" href="javascript:void(0)"></a>        </div>        <!--內容地區-->        <div class="modal-body">          <slot name="body">            <p class="notice">{{modal.text}}</p>          </slot>        </div>        <!--尾部,操作按鈕-->        <div class="modal-footer">          <slot name="button">            <a v-if="modal.showCancelButton" href="javascript:void(0)" class="button {{modal.cancelButtonClass}}" v-touch:tap="close(1)">{{modal.cancelButtonText}}</a>            <a v-if="modal.showConfirmButton" href="javascript:void(0)" class="button {{modal.confirmButtonClass}}" v-touch:tap="submit">{{modal.confirmButtonText}}</a>          </slot>        </div>      </div>    </div>  </div>  <div v-show="show" class="modal-backup" transition="fade"></div></template> 

模態框結構分為三部分,分別為頭部、內部地區和操作地區,都提供了slot,可以根據需要定製。

樣式

.modal {  position: fixed;  left: 0;  top: 0;  right: 0;  bottom: 0;  z-index: 1001;  -webkit-overflow-scrolling: touch;  outline: 0;  overflow: scroll;  margin: 30/@rate auto;}.modal-dialog {  position: absolute;  left: 50%;  top: 0;  transform: translate(-50%,0);  width: 690/@rate;  padding: 50/@rate 40/@rate;  background: #fff;}.modal-backup {  position: fixed;  top: 0;  right: 0;  bottom: 0;  left: 0;  z-index: 1000;  background: rgba(0, 0, 0, 0.5);}

這裡只是一些基本樣式,沒什麼好說的,這次項目是在移動端,用了淘寶的調適型配置方案,@rate是切稿時候的轉換率。

介面定義

/** * modal 模態介面參數 * @param {string} modal.title 模態框標題 * @param {string} modal.text 模態框內容 * @param {boolean} modal.showCancelButton 是否顯示取消按鈕 * @param {string} modal.cancelButtonClass 取消按鈕樣式 * @param {string} modal.cancelButtonText 取消按鈕文字 * @param {string} modal.showConfirmButton 是否顯示確定按鈕 * @param {string} modal.confirmButtonClass 確定按鈕樣式 * @param {string} modal.confirmButtonText 確定按鈕標文字 */props: ['modalOptions'],computed: {  /**   * 格式化props進來的參數,對參數賦予預設值   */  modal: {    get() {      let modal = this.modalOptions;      modal = {        title: modal.title || '提示',        text: modal.text,        showCancelButton: typeof modal.showCancelButton === 'undefined' ? true : modal.showCancelButton,        cancelButtonClass: modal.cancelButtonClass ? modal.showCancelButton : 'btn-default',        cancelButtonText: modal.cancelButtonText ? modal.cancelButtonText : '取消',        showConfirmButton: typeof modal.showConfirmButton === 'undefined' ? true : modal.cancelButtonClass,        confirmButtonClass: modal.confirmButtonClass ? modal.confirmButtonClass : 'btn-active',        confirmButtonText: modal.confirmButtonText ? modal.confirmButtonText : '確定',      };      return modal;    },  },},

這裡定義了介面的參數,可以自訂標題、內容、是否顯示按鈕和按鈕的樣式,用一個computed來做參數預設值的控制。

模態框內部方法

data() {  return {    show: false,  // 是否顯示模態框    resolve: '',    reject: '',    promise: '', // 儲存promise對象  };},methods: {  /**   * 確定,將promise斷定為完成態   */  submit() {    this.resolve('submit');  },  /**   * 關閉,將promise斷定為reject狀態   * @param type {number} 關閉的方式 0表示關閉按鈕關閉,1表示取消按鈕關閉   */  close(type) {    this.show = false;    this.reject(type);  },  /**   * 顯示confirm彈出,並建立promise對象   * @returns {Promise}   */  confirm() {    this.show = true;    this.promise = new Promise((resolve, reject) => {      this.resolve = resolve;      this.reject = reject;    });    return this.promise;  //返回promise對象,給父級組件調用  },},

在模態框內部定義了三個方法,最核心部分confirm方法,這是一個定義在模態框內部,但是是給使用模態框的父級組件調用的方法,該方法返回的是一個promise對象,並將resolve和reject存放於modal組件的data中,點擊取消按鈕時,斷定為reject狀態,並將模態框關閉掉,點確定按鈕時,斷定為resolve狀態,模態框沒有關閉,由調用modal組件的父級組件的回調處理完成後手動控制關閉模態框。

調用

<!-- template --><confirm v-ref:dialog :modal-options.sync="modal"></confirm><!-- methods -->this.$refs.dialog.confirm().then(() => {  // 點擊確定按鈕的回調處理  callback();  this.$refs.dialog.show = false; }).catch(() => {  // 點擊取消按鈕的回調處理  callback();});

用v-ref建立一個索引,就很方便拿到模態框組件內部的方法了。這樣一個模態框組件就完成了。

其他實現方法

在模態框組件中,比較難實現的應該是點擊確定和取消按鈕時,父級的回調處理,我在做這個組件時,也參考了一些其實實現方案。

使用事件轉寄

這個方法是我的同事實現的,用在上一個項目,採用的是$dispatch和$broadcast來派發或廣播事件。

首先在根組件接收dispatch過來的transmit事件,再將transmit事件傳遞過來的eventName廣播下去

events: {  /**   * 轉寄事件   * @param {string} eventName 事件名稱   * @param {object} arg    事件參數   * @return {null}   */  'transmit': function (eventName, arg) {    this.$broadcast(eventName, arg);  }},

其次是模態框組件內部接收從父級組件傳遞過來的確定和取消按鈕所觸發的事件名,點擊取消和確定按鈕的時候觸發

// 接收事件,獲得需要取消和確定按鈕的事件名events: {  'tip': function(obj) {    this.events = {      cancel: obj.events.cancel,      confirm: obj.events.confirm    }  }}// 取消按鈕cancel:function() {  this.$dispatch('transmit',this.events.cancel);}// 確定按鈕submit: function() {  this.$dispatch('transmit',this.events.submit);}

在父級組件中調用模態框如下:

this.$dispatch('transmit','tip',{  events: {    confirm: 'confirmEvent'  }});this.$once('confirmEvent',function() {  callback();}

先是傳遞tip事件,將事件名傳遞給模態框,再用$once監聽確定或取消按鈕所觸發的事件,事件觸發後進行回調。

這種方法看起來是不是很暈?所以vue 2.0取消了$dispatch和$broadcast,我們在最近的項目中雖然還在用1.0,但是也不再用$dispatch和$broadcast,方便以後的升級。

使用emit來觸發

這種方法來自vue-bootstrap-modal,點擊取消和確定按鈕的時候分別emit一個事件,直接在組件上監聽這個事件,這種做法的好處是事件比較容易追蹤。

// 確定按鈕ok () {  this.$emit('ok');  if (this.closeWhenOK) {    this.show = false;  }},// 取消按鈕cancel () {  this.$emit('cancel');  this.show = false;},

調用:

<modal title="Modal Title" :show.sync="show" @ok="ok" @cancel="cancel">  Modal Text</modal>

但是我們在使用的時候經常會遇到這樣的情境,在一個組件的內部,經常會用到多個對話方塊,對話方塊可能只是文字有點區別,回調不同,這時就需要在template中為每個對話方塊都寫一次,有點麻煩。

參考資料

vue.js dynamic create nest modal
es6 Promise對象
vue-bootstrap-modal

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.