主要有標題、內容、按鈕個數、按鈕顏色、按鈕文案這些可配置項javascript
不須要等待用戶二次確認html
import Modal from 'common/components/modal' handleModal() { Modal({ title: '賺取收益?', content: '根據您的受權金額和計息天數計算得出(還未到帳)。實際以到帳金額爲準。', confirmText: '我知道了' }) }
須要等待用戶二次確認vue
import Modal from 'common/components/modal' async handleModal() { await Modal({ title: '肯定如今申請結束嗎?', content: '申請後預計1-5個工做日可退出', cancelColor: '#ff7400', confirmColor: '#000', showCancel: true }) }
common/components/modal/modal.vue
java
這裏用 transition 來包裹動畫,填好配置參數就好了app
handleConfirm() 二次確認事件咱們不放這裏實現,具體緣由後面會講
<template> <transition name="modal-pop"> <div class="wrap" v-show="visible"> <div class="modal"> <h3>{{ title }}</h3> <p>{{ content }}</p> <div class="btns"> <span v-if="showCancel" @click="visible = false" :style="`color: ${cancelColor}`">{{ cancelText }}</span> <span @click="handleConfirm()" :style="`color: ${confirmColor}`">{{ confirmText }}</span> </div> </div> </div> </transition> </template> <style lang="less"> @import './modal.less'; </style>
定義好 props 參數列表,visible 做爲組件內部狀態控制彈框打開關閉less
export default { props: [ 'title', 'content', 'showCancel', 'cancelColor', 'cancelText', 'confirmText', 'confirmColor' ], data() { return { visible: false } } }
common/components/modal/index.js
async
先利用 vue 的 extend 拿到剛編寫的模板動畫
import Vue from 'vue' const ModalConstructor = Vue.extend(require('./modal.vue')) const Modal = (opts = {}) => { let _m = new ModalConstructor({ el: document.createElement('div') }) } export default Modal
配置好默認參數,並將 visible 狀態打開以顯示彈框,最終插入頁面ui
import Vue from 'vue' const ModalConstructor = Vue.extend(require('./modal.vue')) const Modal = (opts = {}) => { let _m = new ModalConstructor({ el: document.createElement('div') }) _m.title = opts.title || '提示' _m.content = opts.content || '' _m.showCancel = opts.showCancel || false _m.cancelText = opts.cancelText || '取消' _m.cancelColor = opts.cancelColor || '#000' _m.confirmText = opts.confirmText || '肯定' _m.confirmColor = opts.confirmColor || '#ff7400' _m.visible = true document.body.appendChild(_m.$el) } export default Modal
用戶點擊二次確認事件後,爲了方便組件外部捕捉,這裏使用 Promise 包裝回調事件spa
這樣 handleConfirm() 放在這裏實現是否是就方便不少了
import Vue from 'vue' const ModalConstructor = Vue.extend(require('./modal.vue')) const Modal = (opts = {}) => { let _m = new ModalConstructor({ el: document.createElement('div') }) _m.title = opts.title || '提示' _m.content = opts.content || '' _m.showCancel = opts.showCancel || false _m.cancelText = opts.cancelText || '取消' _m.cancelColor = opts.cancelColor || '#000' _m.confirmText = opts.confirmText || '肯定' _m.confirmColor = opts.confirmColor || '#ff7400' _m.visible = true document.body.appendChild(_m.$el) return new Promise(resolve => { return (_m.handleConfirm = () => { _m.visible = false resolve() }) }) } export default Modal
import Modal from 'common/components/modal' async handleModal() { await Modal({ title: '肯定如今申請結束嗎?', content: '申請後預計1-5個工做日可退出', cancelColor: '#ff7400', confirmColor: '#000', showCancel: true }) console.log('用戶確認了!') }