当前位置: 首页 > Web前端 > vue.js

vue组件封装-加载框

时间:2023-03-31 14:54:26 vue.js

.loadEffect{width:100px;高度:100px;位置:相对;保证金:0自动;顶部:-60%;z-指数:9999;span{显示:内联块;宽度:20px;高度:20px;边界半径:50%;背景:#Fa3;位置:绝对;动画:加载1.04s缓动无限;&:nth-child(1){左:0;顶部:50%;边距顶部:-10px;动画延迟:0.13s;}&:nth-child(2){左:14px;顶部:14px;动画延迟:0.26s;}&:nth-child(3){左:50%;顶部:0;左边距:-10px;动画延迟:0.39s;}&:nth-child(4){顶部:14px;右:14px;动画延迟:0.52s;}&:nth-child(5){右:0;顶部:50%;边距顶部:-10px;动画延迟:0.65s;}&:nth-child(6){右:14px;底部:14px;动画延迟:0.78s;}&:nth-child(7){底部:0;左:50%;左边距:-10px;动画延迟:0.91s;}&:nth-child(8){底部:14px;左:14px;动画延迟:1.04s;}}@keyframes加载{0%{transform:规模(1.2);不透明度:1;}100%{转换:比例(.3);不透明度:0.5;}}}在前端开发中很多地方都需要用到。下面看看如何在vue中实现一个全局的加载框,并封装在axios中,实现发送请求框时自动显示加载,请求结束时自动关闭加载框。首先构建一个loading.vue的页面.loadEffect{width:100px;高度:100px;位置:相对;保证金:0自动;顶部:-60%;z-指数:9999;span{显示:内联块;宽度:20px;高度:20px;边界半径:50%;背景:#Fa3;位置:绝对;动画:加载1.04s缓动无限;&:nth-child(1){左:0;顶部:50%;边距顶部:-10px;动画延迟:0.13s;}&:nth-child(2){左:14px;顶部:14px;动画延迟:0.26s;}&:nth-child(3){左:50%;顶部:0;左边距:-10px;动画延迟:0.39s;}&:nth-child(4){顶部:14px;右:14px;动画延迟:0.52s;}&:nth-child(5){右:0;顶部:50%;边距顶部:-10px;动画延迟:0.65s;}&:nth-child(6){右:14px;底部:14px;动画延迟:0.78s;}&:nth-child(7){底部:0;左:50%;左边距:-10px;动画延迟:0.91s;}&:nth-child(8){底部:14px;左:14px;动画延迟:1.04s;}}@keyframes加载{0%{transform:规模(1.2);不透明度:1;}100%{转换:比例(.3);不透明度:0.5;}}}为了调用方便,我们需要将加载组件封装为一个函数调用APIVue.extend()可以生成一个Vue子类的构造函数,因为加载组件本身就是一个Vue实例,使用作为生成子类构造函数的参数。只要对加载的加载元素el进行动态操作,就可以实现加载组件的函数调用。创建loading.js,实现如下:importVuefrom'vue';importloadingfrom'./loading.vue';//ExtendedinstanceconstructorconstLoadingConstructor=Vue.extend(loading);//创建一个vue实例,hangloading元素为新创建的divletinitLoadingInstance=function(){returnnewLoadingConstructor({el:document.createElement('div'),});}//删除dom节点letremoveDom=(node)=>{if(node.parentNode){node.parentNode.removeChild(node);}};letinstance=initLoadingInstance();//关闭loadingletcloseLoading=()=>{removeDom(instance.$el)};//显示loadingletshowLoading=function(){document.body.appendChild(instance.$el);}exportdefault{showLoading,closeLoading}这样调用函数showLoading()和closeLoading()就可以显示和关闭加载框了。实现了加载框的功能调用,那么如何在请求发送开始时自动调用加载框,请求结束时自动关闭加载框,这就涉及到请求和响应的拦截。axios拦截请求和响应我们使用axios作为ajax请求的处理框架。axios支持请求拦截和响应。具体可以参考axios文档,然后在main.js中引入axios,在其请求拦截器中显示加载框,在响应中拦截浏览器中关闭加载框。代码如下://引入jsimportloadingfrom'./components/common/loading.js'//拦截请求axios.interceptors.request.use(function(config){//显示loadingloading.showLoading()console之前发送请求.log('requestinterception')returnconfig;},function(error){//Dosomethingabouttherequesterrorconsole.log('requesterrorhandling')returnPromise.reject(error);});//拦截响应axios.interceptors.response.use(function(response){//响应后关闭加载loadingloading.closeLoading()console.log('responseinterception')returnresponse;},function(error){//response错误也关闭loadingloading.closeLoading()console.log('responseerror')returnPromise.reject(error);});