添加自定义toast
需求背景:钉钉h5微应用,使用vue开发,自定义toast,可全局调用,responseFilter拦截器过滤请求时也需要用到
参数控制:自定义显示文字,显示时间
创建Toast.vue
<template>
<div class="toast" v-show="ifShow">
<div>
{{message}}
</div>
</div>
</template>
<script>
export default {
name:'Toast',
data() {
return {
message: '',
ifShow: false
}
},
methods: {
show(message='默认文字',duration=2000){
this.ifShow = true;
this.message = message;
setTimeout(()=>{
this.ifShow=false;
this.message='';
},duration)
}
},
}
</script>
<style scoped>
.toast{
position: fixed;
top: 50%;
left:50%;
transform: translate(-50%,-50%);
padding: 8px 10px;
border-radius: 8px;
z-index:999;
color: white;
background-color: rgba(0, 0, 0, .5)
}
</style>
封装toast
import Toast from './Toast.vue'
const obj = {}
obj.install = function(Vue){
// 1.创建组件构造器
const toastContructor = Vue.extend(Toast)
// 2.new的方式,根据组件构造器,可以创建出一个组件对象
const toast = new toastContructor()
// 3.将组件对象手动挂载到某一个元素上
toast.$mount(document.createElement('div'))
// 4.toast.$el对应的就是div
document.body.appendChild(toast.$el)
Vue.prototype.$toast = toast;
}
export default obj
main.js全局引用
import Vue from 'vue'
import App from './App'
import toast from '@/components/toast'
Vue.use(toast)
let vm = new Vue({
...
}).$mount('#app')
export default vm; //向外暴露vue实例,便于respone拦截器处使用toast实例
普通vue组件
可直接使用
this.$toast.show('已加载全部数据',1000)
axios的封装文件(含拦截器)
无法直接获取vue实例的js文件内,引入vue实例再进行调用
import vm from '@/main.js' //引入vue实例
...
//response拦截器
addResponseFilter() {
// respone 拦截器 axios 的一些配置
this.service.interceptors.response.use(
response => {
...
if (response.data.code === 701) {
vm.$toast.show('请重新登录',2000) //直接使用
return Promise.reject(response)
}
return Promise.reject(response)
}
} else {
vm.$toast.show('服务异常!',2000)
return Promise.reject(new Error(response.data.message || 'Error'))
}
},
error => {
...
}
)
return this
}