您的位置:首页 > Web前端 > Vue.js

VUE中封装一个全局的loading组件

2020-07-22 19:15 344 查看

KBK:其实刚刚开始的话,就没有想到要写loading组件,在做项目的时候,等待后台接口渲染的时候样式有点太丑,就想到做一个loading效果,其实作为前端,也可以使用vant element-ui 等,里面就有好多loading样式,但是我又有点太懒,懒得去一个一个的页面进行loading效果,就想到做一个全局的。。。话不多说,干货来了,嘻嘻

1.创建一个

loading.vue
, 里面的内容如下:
(img 是从网上扒拉下来的 ,你也可以选择自己喜欢的图片哦 )

<template>
<div class="loading">
<img
width="150"
src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1594987125387&di=bf0899070555ffe803df2da2d11f3025&imgtype=0&src=http%3A%2F%2Fimg4.imgtn.bdimg.com%2Fit%2Fu%3D3458475739%2C295617657%26fm%3D214%26gp%3D0.jpg"
alt
/>
</div>
</template>

<script>
export default {
name: "",
data() {
return {};
},
props: {},
components: {},
mounted() {},
methods: {}
};
</script>

<style scoped>
.loading {
background: rgba(0, 0, 0, 0.5);
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
z-index: 500;
}
</style>
  1. main.js
    里面引入一下 将其设置为 全局的
// 全局组件的引入    form 后面 标清 loading 路径 因为我的是放在components里面的
import Loading from '@/components/Loading'
// 全局组件的使用
Vue.component('Loading',Loading)
  1. App.vue
<Loading ></Loading>

这样全局才完成

  1. 那么想要在接口返回的过程中出现loading加在效果, 我是和
    vuex
    一起使用的,用vuex中的全局状态控制这个组件的隐藏显示(可以在任意组件中,可以控制loading隐藏显示)
    ,我在
    state
    里面:
state: {
isLoading:false,
},
  1. 我的
    main.js
    中不是通过
    axios
    写入请求拦截器和响应拦截器了吗,然后就直接加上一个条件
    request
    (请求中) 改变vuex中的isLoading状态数据,当为true,loading显示
    response
    (响应中) 如果返回的状态码为200,说明接口请求成功,可以loading隐藏
// 请求拦截器
axios.interceptors.request.use(
config => {
// 改变vuex中的isLoading状态数据,当为true,loading显示
store.state.isLoading = true
return config;
},
error => {
return Promise.error(error);
}
);

// 响应拦截器
axios.interceptors.response.use(
response => {
// 如果返回的状态码为200,说明接口请求成功,可以正常拿到数据
// 否则的话抛出错误
if (response.status === 200) {
//loading隐藏
store.state.isLoading = false
return Promise.resolve(response);
} else {
return Promise.reject(response);
}
},
error => {
if (error.response.status) {
return Promise.reject(error.response);
}
}
);
  1. 当然了 在
    App.vue
    中进行了改变,就是加上了
    v-if
    判断条件为state里面isLoading 的 true 或者 false
<Loading v-if="$store.state.isLoading"></Loading>
  1. 其实到现在就完成了基本操作了,对于loading效果,你也可以选择局部的,毕竟需求不一样嘛,嘻嘻
    Ending。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: