常常遇到經常使用組件與設計圖有微小區別的狀況,可是自寫組件功能又太單一(劃掉 其實緣由就是懶),這個時候對組件封裝就頗有用處
例如對 element 的 MessageBox 二次封裝css
例如 MessageBox 可自定義配置不一樣內容。vue
<template> <el-button type="text" @click="open">點擊打開 Message Box</el-button> </template> <script> export default { methods: { open() { const h = this.$createElement; this.$msgbox({ title: '消息', message: h('p', null, [ h('span', null, '內容能夠是 '), h('i', { style: 'color: teal' }, 'VNode') ]), showCancelButton: true, confirmButtonText: '肯定', cancelButtonText: '取消', beforeClose: (action, instance, done) => { if (action === 'confirm') { instance.confirmButtonLoading = true; instance.confirmButtonText = '執行中...'; setTimeout(() => { done(); setTimeout(() => { instance.confirmButtonLoading = false; }, 300); }, 3000); } else { done(); } } }).then(action => { this.$message({ type: 'info', message: 'action: ' + action }); }); } } } </script>
那麼就能夠根據組件的自定義內容去封裝一個符合設計需求的組件element-ui
index.jsasync
import { MessageBox } from 'element-ui' import './ConfirmBox.scss' export default function( title = '提示', message = '提示內容', icon = 'warning' ) { const h = this.$createElement return MessageBox({ message: h('div', null, [ h( 'div', { class: { 'confirm-box-header': true } }, [ h('svg-icon', { props: { 'icon-class': icon, 'class-name': 'confirm-box-icon' } }), h( 'span', { class: { 'confirm-box-title': true } }, title ) ] ), h( 'div', { class: { 'confirm-box-message': true } }, message ) ]), customClass: 'confirm-box', showCancelButton: true, confirmButtonText: '肯定', cancelButtonText: '取消' }) }
ConfirmBox.scsside
.confirm-box { padding-bottom: 24px; .el-message-box__content { padding: 36px 24px; .confirm-box-header { display: flex; flex-direction: row; justify-content: flex-start; align-items: center; } .confirm-box-icon { width: 16px; height: 16px; } .confirm-box-title { display: block; padding-left: 12px; font-size: 16px; font-weight: 500; color: $primary-font; line-height: 24px; } .confirm-box-message { padding: 12px 0 0 28px; font-size: 14px; font-weight: 400; color: $primary-font; line-height: 22px; } } }
main.js 加如下兩行svg
import ConfirmBox from '@/components/ConfirmBox' Vue.prototype.$confirmBox = ConfirmBox
使用效果 看起來好像像那麼回事(雖然不是自寫組件,可是寫起來快啊)
flex
this.$confirmBox( '我大標題', '我是內容' ) .then(async () => { }) .catch(() => {})