1.在全局components文件下新增toast文件夹,再分别建立index.vue与index.js两个文件;
index.vue文件:
<template>
<view>
<view class="toast-container" v-if="isShow">
<!-- 0 成功,1失败,2错误 -->
<view class="toast" v-if="type !==3">
<image :src="toastImgUrl[type]" class="show-icon"></image>
<view>{{ msg }}</view>
</view>
<!-- 无图标样式提示 -->
<view class="toast-no-icon" v-if="type == 3">
<view class="toast-msg">{{ msg }}</view>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
toastImgUrl:[
require('@/static/common/toastSuccess.png'),
require('@/static/common/toastFail.png'),
require('@/static/common/toastError.png'),
'',
],
};
}
};
</script>
<style lang="scss" scoped>
.toast-container {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 999;
.toast,.toast-no-icon {
width: 220rpx;
background: rgba(0, 0, 0, 0.65);
border-radius: 20rpx;
text-align: center;
color: #FFFFFF;
font-size: 32rpx;
padding:48rpx 22rpx;
line-height: 48rpx;
}
.show-icon {
width: 56rpx;
height: 56rpx;
display: inline-block;
margin-bottom: 20rpx;
}
.toast-no-icon{
width: 448rpx;
height: 130rpx;
padding: 23rpx 32rpx;
font-size: 32rpx;
}
}
</style>
index.js文件:
import vue from 'vue';
import Toast from './index.vue';
//生成构造函数
const toastConstructor = vue.extend(Toast);
let showToast = false;
// type 0 成功(√),1失败(x),2警示(感叹号),3(不带符号图标)
function openToast(text,type,time = 3000){
if(showToast){
return
}
showToast = true;
let newDom = new toastConstructor({
el: document.createElement('div'),
data() {
return{
msg: text,
isShow: true,
type:type
}
}
});
document.body.appendChild(newDom.$el);
setTimeout(()=>{
newDom.isShow = false;
showToast = false;
},time)
}
// 全局组件,挂载到vue原型上
function regFn(){
vue.prototype.$toast = openToast
}
export default regFn
2.在main.js文件
import toastComponent from './components/toast/index.js';
Vue.use(toastComponent)