VUE2實現事件驅動彈窗樣本,vue2事件彈窗樣本

來源:互聯網
上載者:User

VUE2實現事件驅動彈窗樣本,vue2事件彈窗樣本

前幾天想瞭解vue如何寫彈窗組件

有以下兩種可取的寫法:

1.狀態管理 如果彈窗組件放在根組件,使用vuex來管理組件的show和hide。放在組件內,通過增加v-show或v-if來控制,可結合slot,定義不同需求的彈窗

2.事件管理 註冊一個全域事件來開啟彈窗,傳入需展示的文字和相關的邏輯控制,可結合promise,實現非同步

覺得對用像confirme和propmt這類彈窗,還是事件驅動的好。最好就是能使用promise回調。

於是手癢就寫了一個。下面是代碼。

propmt.js

import Vue from 'vue'import promptComponent from './prompt.vue' // 引入彈窗的vue檔案const promptConstructor = Vue.extend(promptComponent); // 註冊組件let instance = new promptConstructor().$mount(''); // 獲得組件的執行個體document.body.appendChild(instance.$el); // 將組件的element插入到body中const Alert = (text,okText)=>{  if(instance.show === true) { //防止多次觸發    return;  }  // 為彈窗資料賦值  instance.show = true;   instance.isAlert = true;  instance.okText = okText||'確定';  instance.message = text;  //返回一個promise對象,並為按鈕添加事件監聽  return new Promise(function(resolve,reject) {    instance.$refs.okBtn.addEventListener('click',function() {      instance.show = false;      resolve(true);    })  })};const Confirm = (text,okText,cancelText)=>{  if(instance.show === true) {    return;  }  instance.show = true;  instance.okText = okText||'確定';  instance.cancelText = cancelText||'取消';  instance.message = text;  return new Promise(function(resolve,reject) {    instance.$refs.cancelBtn.addEventListener('click',function() {      instance.show = false;      resolve(false);    });    instance.$refs.okBtn.addEventListener('click',function() {      instance.show = false;      resolve(true);    })  })};const Prompt = (text,okText,inputType, defaultValue)=>{  if(instance.show === true) {    return;  }  instance.show = true;  instance.isPrompt = true;  instance.okText = okText||'確定';  instance.message = text;  instance.inputType = inputType || 'text';  instance.inputValue = defaultValue || '';  return new Promise(function(resolve,reject) {    instance.$refs.okBtn.addEventListener('click',function() {      instance.show = false;      resolve(instance.inputValue);    })  })};export {Alert,Confirm,Prompt}

prompt.vue

<style lang="less" scoped>  .confirm-enter-active {    transition: all .2s;  }  .confirm-leave-active {    transition: opacity .2s;  }  .confirm-leave-to {    opacity: 0;  }  .confirm-enter {    opacity: 0;  }  .confirm {    position: relative;    font-family: PingFangSC-Regular;    font-size: 17px;    -webkit-user-select: none;    user-select: none;    // 遮罩層樣式    .masker {      position: fixed;      top: 0;      left: 0;      width: 100%;      height: 100%;      background-color: rgba(0, 0, 0, .4);      -webkit-transition: opacity .1s linear;      transition: opacity .1s linear;      z-index: 100;    }    // 入庫資料錯誤樣式    .box {      position: absolute;      top: 50%;      left: 50%;      width: 72%;      -webkit-transform: translate(-50%, -50%);      transform: translate(-50%, -50%);      text-align: center;      border-radius: 12px;      background-color: #fff;      .message {        height: 97px;        line-height: 24px;        font-family: PingFangSC-Regular;        font-size: 17px;        vertical-align: middle;        color: #999;        letter-spacing: -0.41px;        p {          margin: 20px auto 0 auto;          vertical-align: middle;        }        &::after {          content: '';          height: 100%;        }      }      .prompt {        margin: 20px 0;        width: 100%;        p {          margin: 5px auto;          font-size: 17px;          line-height: 24px;        }        input {          margin: 5px auto;          border: 1px solid #333;          border-radius: 6px;          width: 100px;          height: 30px;          font-size: 14px;          line-height: 20px;          text-align: center;        }      }      .button-group {        a {          width: calc(50% - 0.5px);          text-align: center;          font-size: 17px;          line-height: 43px;          color: blue;        }        .max-width {          width: 100% !important;;        }      }    }  }</style><template>  <transition name="confirm">    <div class="confirm" v-show="show">      <div class="masker" @touchmove.prevent>        <div class="box">          <div class="message" v-if="!isPrompt">            <p>{{message}}</p>          </div>          <div class="prompt" v-if="isPrompt">            <p>{{message}}</p>            <input type="text" v-model="inputValue" v-if="inputType === 'text'" ref="inputEl">            <input type="tel" v-model.number="inputValue" @keydown="enterCheck" v-if="inputType === 'tel'" ref="inputEl">          </div>          <div class="button-group clearfix bd-top">            <a class="bd-right fl" ref="cancelBtn" v-show="!isAlert && !isPrompt">{{cancelText}}</a>            <a class="fr" ref="okBtn" :class="{'max-width': isAlert || isPrompt}">{{okText}}</a>          </div>        </div>      </div>    </div>  </transition></template><script type="text/ecmascript-6">  import {mapState} from 'vuex'  export default{    data() {      return {        show: false,        message: '請輸入提示',        okText: '確定',        cancelText: '取消',        isAlert: false,        isPrompt: false,        inputValue: '',        inputType: ''      }    },    methods: {      // 金額輸入框校正      enterCheck(event) {        // 只允許輸入數字,刪除鍵,11位元字        if (event.keyCode === 46 || event.keyCode === 8) {          return;        }        if (event.keyCode < 47 || event.keyCode > 58 || event.keyCode === 190) {          event.returnValue = false;        }      },    },    watch: {      show(){        if (this.show) {          this.$nextTick(() => {            console.log(this.$refs.inputEl);            console.log(this.inputType);            this.$refs.inputEl.focus();          });        }      }    }  }</script>

main.js

import {Alert,Prompt,Confirm} from '../lib/components/prompt/prompt.js'Vue.prototype.Alert = function(text,okText) {  return Alert(text,okText)};Vue.prototype.Confirm = function(text,okText,cancelText) {  return Confirm(text,okText,cancelText)};Vue.prototype.Prompt = function(text,okText,inputType, defaultValue) {  return Prompt(text,okText,inputType, defaultValue)};component.vue:inputName() {  this.Prompt('請輸入名稱','確認','text').then(res =>{    // do something use res  });},

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.