微信小程序自定义toast的实现代码

时间:2021-05-18

今天写微信小程序突然发现一个尴尬的问题,请求报错需要提示,就去小程序API里找,可悲的小程序的toast并不能满足我的需求,原生提供的方法调用如下

wx.showToast({ title: '成功', icon: 'succes', duration: 1000, mask:true})

下面是官方API的说明

可以看到支持的图标只有两种,连基本的warning和error都没有,最可悲的是title最多只支持7个汉字的长度,完全不能忍啊,现在哪个框架里还没有个正儿八经提示框的组件,想想还是自己写一个算了,下面是效果图

下面来说下小程序实现自定义公共组件的方法,以自定义toast为例

1、新建toast组件

在toast.json里修改如下,设置为组件

{ "component": true}

toast.wxml

<view class='wx-toast-box' animation="{{animationData}}"> <view class='wx-toast-content'> <view class='wx-toast-toast'>{{ content }}</view> </view></view>

定义样式,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中调用组件

<view> <toast id='toast'> </toast></view>

login.js里点击登陆录的时候调用显示showDialog方法

onReady: function () { this.toast = this.selectComponent("#toast");},listenerLogin: function() { this.dialog.showToast('恭喜你,获得了toast');},

总结

以上所述是小编给大家介绍的微信小程序自定义toast的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章