CustomToast.vue
<template>
<view v-if="visible" class="custom-toast">
<view class="toast-content">
<text>{{ message }}</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
visible: false,
message: '',
duration: 2000,
timer: null
};
},
methods: {
show(message, duration = 2000) {
this.message = message;
this.visible = true;
clearTimeout(this.timer);
this.timer = setTimeout(() => {
this.visible = false;
}, duration);
}
}
};
</script>
<style scoped>
.custom-toast {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 9999;
pointer-events: none;
}
.toast-content {
background: rgba(0, 0, 0, 0.75);
color: #fff;
padding: 20rpx 30rpx;
border-radius: 16rpx;
font-size: 28rpx;
max-width: 80%;
text-align: center;
}
</style>
toast.js
import Vue from 'vue'
import CustomToast from '@/components/CustomToast.vue'
const ToastConstructor = Vue.extend(CustomToast)
let toastInstance = null
function createToastInstance() {
toastInstance = new ToastConstructor()
toastInstance.$mount()
const app = getApp().$vm
app.$children[0].$el.appendChild(toastInstance.$el)
}
export default {
install(Vue) {
Vue.prototype.$toast = (msg, duration = 2000) => {
if (!toastInstance) {
createToastInstance()
}
toastInstance.show(msg, duration)
}
}
}
main.js中引用
import Vue from 'vue'
import Toast from './plugins/toast.js'
Vue.use(Toast)