微信小程序实现自定义组件之弹窗
组件实现
<!--components/popup/popup.wxml-->
<view class="pop-mask {{show ? 'pop-active': ''}}" bind:tap="onClose"></view>
<view class="pop-main {{popPosition}}" style="width: {{width}};">
<view class="pop-title" wx:if="{{title}}">{{title}}</view>
<slot></slot>
</view>
// components/popup/popup.ts
Component({
properties: {
show: {
type: Boolean,
value: false
},
title: {
type: String,
value: ""
},
position: {
type: String,
value: "bottom" // bottom\top\center
},
width: {
type: String,
value: "750rpx"
}
},
data: {
popPosition: 'pop-bottom',
},
observers: {
// 计算位置
'show': function (show) {
var position = this.data.position
var popPosition =
!show ? ''
: position == 'bottom' ? 'pop-bottom'
: position == 'top' ? 'pop-top'
: position == 'center' ? 'pop-center' : '';
this.setData({ popPosition: popPosition })
}
},
methods: {
onShow() {
// 触发显示事件,对应父组件的 bind:show
this.triggerEvent('show')
},
onClose() {
this.triggerEvent('close')
},
}
})
/* components/popup/popup.wxss */
@import "../../app.less";
.pop-mask {
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
background-color: var(--overlay-background-color, rgba(0, 0, 0, .7));
z-index: 10;
display: none;
}
.pop-main {
width: 100%;
min-height: 200px;
background-color: #fff;
border-radius: @borderRadius;
padding: @marginBottom;
position: fixed;
left: 50%;
bottom: 0%;
transform: translateY(100%) translateX(-50%);
transition: all .3s ease-out;
z-index: 31;
.pop-title {
font-size: 17px;
font-weight: bold;
color: #2e2e2e;
padding: 10px;
text-align: center;
}
}
.pop-bottom {
top: unset;
bottom: 0;
transform: translateY(0%) translateX(-50%);
}
.pop-center {
bottom: 50%;
transform: translateY(50%) translateX(-50%);
}
.pop-top {
bottom: 100%;
transform: translateY(100%) translateX(-50%);
}
.pop-active {
display: block;
}
@keyframes show {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@keyframes up {
0% {
transform: translateY(100%);
}
100% {
opacity: 1;
transform: translateY(0);
}
}
使用
json引入
{
"usingComponents": {
"popup": "/components/popup/popup"
}
}
wxml
<popup show="{{show}}" title="赞赏" position='center' width='680rpx'
bind:show="onShow"
bind:close="onClose">
<view>center </view>
</popup>
js
Component({
data: {
showAppreciate: false,
},
methods: {
onShow() {
this.setData({ show: true })
},
onClose() {
this.setData({ show: false })
}
}
})