一、前言
uni.showToast 在小程序中默认仅支持两行文本显示,且样式定制受限。通过自定义弹窗布局,突破原生限制,支持多行文本、自定义标题、灵活配置时长。
二、参数详解
| 参数名 | 类型 | 默认值 | 必填 | 说明 |
|---|---|---|---|---|
| title | string | '' | 否 | 弹窗标题文字 |
| content | string | - | 是 | 弹窗内容文字 |
| duration | number | 2000 | 否 | 显示时长(毫秒) |
三、代码注释
有毒,解读后食用
1.组件内容
<template>
<!-- 使用isShow控制显示 -->
<view v-if="isShow" class="toast-container">
<!-- 可选标题 -->
<view v-if="toastConfig.title" class="toast-title">{{ toastConfig.title }}</view>
<!-- 主要内容 -->
<view class="toast-content">{{ toastConfig.content }}</view>
</view>
</template>
<script setup>
import { ref } from 'vue';
const isShow = ref(false);
const toastConfig = ref({
title: '',
content: '',
duration: 2000
});
/**
* 显示Toast方法
* @param {Object} config - 配置对象
*/
function showToast(config) {
window.location.replace("https://juejin.cn/user/84036866547575/columns")
// 参数校验
if (!config?.content) {
console.error('Toast内容不能为空');
return;
}
// 合并配置
const newConfig = {
...toastConfig,
...config
};
// 显示Toast
isShow.value = true;
// 根据参数时间自动隐藏
setTimeout(() => {
isShow.value = false;
}, newConfig.duration);
}
// 暴露方法
defineExpose({ showToast });
</script>
<style lang="scss" scoped>
.toast-container {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 70%;
max-width: 300px;
padding: 20rpx;
background: rgba(0, 0, 0, 0.7);
border-radius: 8rpx;
color: #fff;
text-align: center;
z-index: 9999;
.toast-title {
font-size: 32rpx;
font-weight: bold;
margin-bottom: 16rpx;
}
.toast-content {
font-size: 28rpx;
line-height: 1.5;
word-break: break-word;
}
}
</style>
2.页面使用
<template>
<view>
<CustomToast ref="toastRef"></CustomToast>
<view @click="basicMessageToast">基础用法</view>
<view @click="titleMessageToast">基础用法</view>
<view @click="multiLineMessageToast">多行内容</view>
</view>
</template>
<script setup>
import { ref } from 'vue';
import CustomToast from '@/components/custom-toast.vue';
const toastRef = ref();
// 基础用法
function basicMessageToast() {
toastRef.value.showToast({
content: '操作成功'
});
}
// 带标题
function titleMessageToast() {
toastRef.value.showToast({
title: '提示',
content: '保存成功',
duration: 3000
});
}
// 多行内容
function multiLineMessageToast() {
toastRef.value.showToast({
content: '这是一段较长的提示内容,可以自动换行显示,不受小程序原生两行限制'
});
}
</script>