如何在微信小程序中自定义toast?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

创新互联建站网站建设服务商,为中小企业提供网站建设、成都做网站服务,网站设计,网站托管、服务器租用等一站式综合服务型公司,专业打造企业形象网站,让您在众多竞争对手中脱颖而出创新互联建站。
1、新建toast组件
在toast.json里修改如下,设置为组件
{
"component": true
}toast.wxml
{{ content }}
定义样式,toast.wxss,这里使用flex布局,代码很简单,也没什么好说的,直接贴上
.wx-toast-box{
display: flex;
width: 100%;
justify-content: center;
position: fixed;
z-index: 999;
bottom:80rpx;
opacity: 0;
}
.wx-toast-content{
max-width: 80%;
border-radius:30rpx;
padding: 30rpx;
background: rgba(0, 0, 0, 0.6);
}
.wx-toast-toast{
height: 100%;
width: 100%;
color: #fff;
font-size: 28rpx;
text-align: center;
}toast.js
Component({
options: {
multipleSlots: true // 在组件定义时的选项中启用多slot支持
},
/**
* 私有数据,组件的初始数据
* 可用于模版渲染
*/
data: { // 弹窗显示控制
animationData: {},
content: '提示内容'
},
/**
* 组件的方法列表
*/
methods: {
/**
* 显示toast,定义动画
*/
showToast(val) {
var animation = wx.createAnimation({
duration: 300,
timingFunction: 'ease',
})
this.animation = animation
animation.opacity(1).step()
this.setData({
animationData: animation.export(),
content: val
})
/**
* 延时消失
*/
setTimeout(function () {
animation.opacity(0).step()
this.setData({
animationData: animation.export()
})
}.bind(this), 1500)
}
}
})2、在父级组件中调用公共组件,以login页面为例
在login.json中注册组件
{
"navigationBarTitleText": "登录注册",
"usingComponents":{
"toast": "../common/toast/toast"
}
}login.wxml中调用组件
login.js里点击登陆录的时候调用显示showDialog方法
onReady: function () {
this.toast = this.selectComponent("#toast");
},
listenerLogin: function() {
this.dialog.showToast('恭喜你,获得了toast');
},看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注创新互联行业资讯频道,感谢您对创新互联的支持。