自从小程序发布以后,越来越多的开发者投入到小程序的开发当中去,而且微信有着相当完善的API和组件,使用起来简单,但是无奈,官方对API和组件的限制太多,想将这些官方的组件或者API运用到实际当中不太可能,所以一下将介绍怎么去写一个自定义的toast组件。
首先,先看一下官方的API的展示形式
用法很简单,直接拷贝官方代码就好,代码如下:
Wx.showToast({
Title:’成功’,
Icon:’success’,
duration:2000
})
下面我将分享怎么自定义toast组件
1、现在component目录下新建一个toastTest目录
2、在toasTest.wxml文件里面新建一个自定义组件模块template,代码如下:
<template name=”toast”>
<view class=”toast_content_box” wx:if=”{{isHide}}”>
<view class=”toast_content”>
<view class=”toast_content_text”>
{{content}}
</view>
</view>
</view>
</view>
</template>
3、接下来就是样式代码,代码如下:
.toast_content_box{
display:flex;
width:100%;
height:100%;
justify_content:center;
align-items:center;
position:fixed;
z-index:999;
}
.toast_conten{
width:50%;
padding:30rpx;
background:rgba(0,0,0,0.8);
broder-radius:20rpx;
}
.toast_conten_text{
width:100%;
height:100%;
color:#fff;
font-size:28rpx;
text-align:center;
}
4、toastTest.js代码如下:
let _compDate={
'_toast_.isHide':false,
'_toast_.content':''
}
let toastPannel={
show:function(data){
let self = this;
this.setData({ '_toast_.isHide':true, '_toast_.content':data});
setTimeout(function(){
self.setData({'_toast_.isHide':false})
},3000)
}
}
function ToastPannel(){
let pages = getCurrentPages();
let curPage = pages[pages.length - 1 ];
this._page=curPage;
Object.assign(curPage,toastPannel);
curPage.toastPannel=this;
curPage.setData(_compDate);
return this;
}
module.exprorts={
ToastPannel
}
其中的toastPannel对象中包含一些自定义方法,ToastPannel是一个构造函数
5、在app.js中将组件脚本注入全局
//app.js
import{ToastPannel} from './component/toastTest/toastTest'
app({
ToastPannel,
})
然后再全局中引入组件样式表:
@import "./component/toastTest/toastTest.wxss";
6、在需要该组件的页面将模块注入
<import src="../../component/toastTest/toastTest.wxml"/>
<template is="toast" data="{{..._toast_}}"/>
<view bindtap="openToastPannel">toastTest测试</view>
7、在当前的JS文件中实例构造函数
Page({
data:{
content:'自定义toast组件'
},
onLoad:function(){
let app = getApp();
new app.ToastPannel();
},
openToastPannel:function(){
this.show(this.data.content);
}
})
8、这就是自定义toast的实现效果啦