vue封装全局loading
第一步在components的文件夹下创建一个Global文件夹(文件夹名称可以随便起)在Global文件夹下创建一个index.js文件,如下图:
在index.js中写入以下代码:
// 要将loading注册为全局组件
import Vue from 'vue'
// 引入组件
import loading from'@/components/loading/loading'
const createloading = Vue.extend(loading)
// 实例化组件 将该组件的挂载点设置为一个自己创建的div
const instence = new createloading({
el:document.createElement('div')
})
// // instence 是一个实例化对象 给当前实例添加一个自定义属性
instence.show = false
const $loading = {
show(tips){
instence.show = true
instence.tips = tips
document.body.appendChild(instence.$el)// $el 其实就是挂载点的dom
},
hide(){
instence.show = false
}
}
export default {
// install 必须写成install 因为 Vue.use() 会调用install
install() {
if(!Vue.$loading) {
Vue.$loading = $loading
}
Vue.mixin({
created() {
this. $loading = Vue.$loading
}
})
}
}
然后在components的文件夹下创建一个loading文件夹,在loading文件夹下创建一个loading.vue子组件,在loading.vue子组件中写入以下代码:
<template>
<div id="loading" v-show="show">
<div>
{{ tips }}
</div>
</div>
</template>
<script>
export default {
name: "loading",
props: {
tips: String,
show: Boolean,
},
data() {
return {};
},
created() {},
methods: {},
};
</script>
<style lang=scss scoped>
#loading {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
div {
max-width: 250px;
// height: 150px;
padding: 15px;
background-color: rgba(0, 0, 0, 0.7);
color: #fff;
font-size: 18px;
border-radius: 6px;
line-height: 24px;
}
}
</style>
最后在封装好的axios请求中写入以下代码:
import axios from 'axios'
import Vue from 'vue'
import $loading from '@/components/Global'
Vue.use( $loading)
const server = axios.create({
baseURL:'https://api.it120.cc/',
timeout:5000//请求超时
})
// 设置请求拦截响应
server.interceptors.request.use((confige)=>{
confige.headers.token = '123468486'//设置token
Vue.$loading.show('拼命加载中...')
// console.log(confige);
return confige;
},(err)=>{
console.log(err);
})
// 设置响应拦截
server.interceptors.response.use((res)=>{
console.log(res);
Vue.$loading.hide()
return res
},(err)=>{
console.log(err);
})
export default server
完成这些一个全局的loading就新鲜出炉啦。
小编也是第一次写博客,同样也是一个刚接触vue不久的小白 所以大佬们勿喷哈