微信小程序-自定義toast
- 微信小程序原生的toast最多能顯示兩行文字。
- 方案1:
- 方案2
微信小程序原生的toast最多能顯示兩行文字。
有時候并不能滿足業務需求。所以我們需要使用第三方或者自定義。
方案1:
第三方vant-toast
微信小程序下載引入第三方vant之后。
在需要使用的頁面json文件里面引入
"usingComponents": {"van-toast": "@vant/weapp/toast/index"
}
wxml頁面增加
<van-toast id="van-toast" />
js或者ts頁面引入
var util = require('../../../utils/util')
import Toast from '@vant/weapp/toast/toast'Page({data: {},// 打開文檔openDocumentClick(e: any) {console.log('下載URL', e)var loadUrl = e.currentTarget.dataset.key.urlwx.downloadFile({url: loadUrl, // 替換為你要下載的文件的 URL success(res) {if (res.statusCode === 200) {console.log(res.tempFilePath)} else {Toast('下載失敗' + res.errMsg);}},fail(err) {Toast('下載失敗' + err);}});},})
以上親測有效,可以顯示多行提示文字。
方案2
自定義toast。在components里面
第一步:新建文件夾
第二步:新建component。
index.scss文件
.toast-container {position: fixed;top: 50%;left: 50%;transform: translate(-50%, -50%);z-index: 9999;
}.toast-content {background-color: rgba(0, 0, 0, 0.7);color: white;padding: 20rpx 30rpx;border-radius: 10rpx;display: flex;flex-direction: column;align-items: center;
}.toast-icon {width: 60rpx;height: 60rpx;margin-bottom: 10rpx;
}.toast-message {font-size: 28rpx;
}
index.wxml文件
<view class="toast-container" wx:if="{{show}}"><view class="toast-content"><image wx:if="{{icon}}" src="{{icon}}" class="toast-icon"></image><text class="toast-message">{{message}}</text></view>
</view>
index.ts文件
Component({properties: {message: String,duration: {type: Number,value: 3000},icon: {type: String,value: ''}},data: {show: false},methods: {showToast() {this.setData({ show: true })setTimeout(() => {this.hideToast()}, this.properties.duration)},hideToast() {this.setData({ show: false })}}
})
上面就是自定義的組件。接下來就是在需要使用的頁面進行調用了。比如在首頁home文件里面使用。
home.json
{ "navigationBarTitleText": "首頁", "navigationStyle":"custom","navigationBarTextStyle":"white","usingComponents": {"van-popup": "@vant/weapp/popup/index","custom-toast": "/components/FT-Toast/index"}
}
home.wxml
<custom-toast id="toast" />
home.ts
var util = require('../../../utils/util')
import Toast from '@vant/weapp/toast/toast'Page({data: {},
showToast(message:any, icon = '') {this.selectComponent('#toast').setData({message,icon})this.selectComponent('#toast').showToast()},
// 打開文檔openDocumentClick(e: any) {console.log('下載URL', e)var loadUrl = e.currentTarget.dataset.key.urlwx.downloadFile({url: loadUrl, // 替換為你要下載的文件的 URL success(res) {if (res.statusCode === 200) {console.log(res.tempFilePath)} else {this.showToast('下載失敗' + res.errMsg)}},fail(err) {this.showToast('下載失敗' + err)}});},})
以上方案親測有效。
以上兩個方法都可以使用,個人建議直接使用vant里面的比較方便。