初识小程序,好多功能都感觉新鲜。由于多个页面都需要弹窗,想着能不能跟安卓一样封装一个方法,所有都页面都能调用。记录如下:
封装模块dialog.js
// component/dialog/dialog.js
Component({
/**
* 组件的属性列表
*/
properties: {
content: {
type: String,
},
confirmText: {
type: String,
},
cancelText: {
type: String,
}
},
/**
* 组件的初始数据
*/
data: {
showDialog: false
},
/**
* 组件的方法列表
*/
methods: {
show() {
this.setData({
showDialog: true
});
},
hide() {
this.setData({
showDialog: false
})
},
/*
* 内部私有方法建议以下划线开头
* triggerEvent 用于触发事件
*/
_cancel() {
//触发取消回调
this.triggerEvent("cancel")
},
_confirm() {
//触发成功回调
this.triggerEvent("confirm");
}
}
})
dialog.wxml
//通过showDialog控制显示
<view class='mask' style='display:{{showDialog?"":"none"}};'>
<view class='mask-window'>
<view class='mask-top'>{{content}}</view>
<view class='mask-bottom'>
//通过bindtap调用dialog.js里边都方法
<view class='cancel' bindtap='_cancel'>{{cancelText}}</view>
<view class='confirm' bindtap='_confirm'>{{confirmText}}</view>
</view>
</view>
</view>
dialog.wxss,弹窗都样式文件
.mask{
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
background: rgba(0, 0, 0, .3);
z-index: 10;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
/* display: none; */
}
.mask-window{
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background: white;
border-radius: 20rpx;
}
.mask-top{
height: 120rpx;
width: 500rpx;
line-height: 120rpx;
text-align: center;
border-bottom: 2rpx solid #ccc;
}
.mask-bottom{
display: flex;
flex-direction: row;
width: 100%;
}
.mask-bottom .confirm{
color: white;
background: #FF2E2E;
border-left: 2rpx solid #ccc;
border-radius: 0 0 20rpx 0;
}
.mask-bottom .cancel, .mask-bottom .confirm{
height: 100rpx;
line-height: 100rpx;
flex: 1;
text-align: center;
}
dialog.json文件,设置
{
//设置可被引用
"component": true,
"usingComponents": {}
}
自此代码封装已经完成了,等待调用(以page页面下advice页面为例)
advice.json引入模块
{
"usingComponents": {
"dialog": "/component/dialog/dialog"
}
}
advice.wxml布局文件中即可使用
<button bindtap="handleSubmit" class="btn">新增资产项目</button>
<dialog id="dialog"
confirmText="确定"
cancelText="取消"
content="{{dialogContent}}"
//cancel和confirm与dialog.js中事件分发的名称一致,
bind:cancel="handleCancelDialog"
bind:confirm="handleConfirmDialog">
</dialog>
advice.wxss样式文件已经不关键,因为dialog.wxss已经设置过了
advice.js文件处理逻辑
// 显示弹窗
handleSubmit:function(){
const dialogContent = '确定要删除吗?';
this.setData({
dialogContent: dialogContent
})
this.dialog.show();
},
// 点击了弹出框的取消
handleCancelDialog() {
this.dialog.hide()
},
// 点击了弹出框的确认
handleConfirmDialog() {
this.dialog.hide()
},