前言
在日常的开发中。有些组件通过import的方式引入可能并不能满足我们的需求,或者某些组件使用的地方比较多。频繁的import也很繁琐。比如像一些dialog,alert等组件,可能在整个项目中都会用到。这时候把组件注册成为全局的通过js来进行调用可能更为方便。
封装dialog组件
一个具有确定和取消功能的组件,具体实现代码如下
//dialog.vue
<template>
<van-overlay :show="showOverlay" >
<div class="content-box">
<span class="cont">{{content.message}}</span>
<div class="bottom-btn">
<span class="cancel-btn" v-if="content.isShowCancelBtn" @click="cancel">取消</span>
<span class="sure-btn" @click="sure">{{content.confirmBtnText}}</span>
</div>
</div>
</van-overlay>
</template>
<script>
export default {
data(){
return {
showOverlay:true,
content:{
message: "",
confirmBtnText: "",
isShowCancelBtn: false
}
}
},
methods:{
cancel(){},
sure(){}
}
}
</script>
<style lang="less" scoped>
@import "~@/style/variables.less";
@import "~@/style/mixin.less";
.content-box{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
.wh(6.1,3.16);
background: #FFFFFF;
border-radius: 0.2rem;
.cont{
width: 100%;
font-size: 0.3rem;
font-family:@font-family;
font-weight: 400;
color: #333333;
text-align: center;
}
.bottom-btn{
width: 100%;
margin-top: 0.6rem;
display: flex;
justify-content: space-around;
align-items: center;
.cancel-btn{
.wh(2.52,0.8);
line-height: 0.8rem;
border-radius: 0.45rem;
border: 0.02rem solid #CCCCCC;
font-size: 0.28rem;
font-family:@font-family;
font-weight: 400;
color: #999999;
text-align: center
}
.sure-btn{
.wh(2.52,0.8);
line-height: 0.8rem;
background: #FF692A;
border-radius: 0.45rem;
font-size: 0.28rem;
font-family:@font-family;
font-weight: 400;
color: #fff;
text-align: center;
}
}
}
</style>
//dialog.js
import Vue from 'vue';
import Overlay from './overlay.vue'
let dialogConstructor = Vue.extend(Overlay);
let thsDialog = function (content) {
return new Promise((res, rej) => {
//promise封装,确认执行resolve,取消执行rejectlet
const dialogDom=new dialogConstructor().$mount()
document.body.appendChild(dialogDom.$el); //new一个对象,然后插入body里面
dialogDom.content = content;
dialogDom.sure = function () {
res()
dialogDom.showOverlay = false
}
dialogDom.cancel = function () {
rej()
dialogDom.showOverlay = false
}
})
}
export default thsDialog;
调用方式
可以通过在main.js文件里引入,然后全局使用。也可以单个组件引入使用
# import dialog from './components/overlay/overlay.js'
dialog({
message: '确认删除这个营业时间吗?',
confirmBtnText: '确认',
isShowCancelBtn: true
}).then(() => {
this.customTimeList.splice(index, 1)
}).catch(() => {})
总结
日常开发中遇到的一些问题,做了一下总结。以便于下次再遇到了能快速定位到问题。上面如有不当的地方,还请指正。