1.src目录下创建plugin文件夹
2.在plugin文件夹下自定义一个文件夹比如(loading)一个文件夹就是一个组件
3.在loading目录下创建Loading.vue
<template>
<div class="container" v-show="isShow">
<div class="loading"></div>
<p class="title">{{title}}</p>
</div>
</template>
<script>
export default {
// eslint-disable-next-line vue/multi-word-component-names
name: 'Loading',
data: function () {
return {
title: '正在加载...',
isShow: false
}
}
}
</script>
<style scoped lang="scss">
.container{
width: 200px;
height: 200px;
border-radius: 20px;
background: rgba(0,0,0,0.5);
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
.loading{
width: 100px;
height: 100px;
border-radius: 50%;
border: 5px solid #fff;
margin: 20px auto;
border-right-color: #409eff;
animation: loading 2s linear infinite;
}
.title{
text-align: center;
font-size: 16px;
color: #fff;
}
}
@keyframes loading {
from{
transform: rotate(0deg);
}
to{
transform: rotate(360deg);
}
}
</style>
4.在loading目录下创建index.js
import Loading from './Loading'
export default {
// 注意点: 如果要将一个组件封装成一个插件, 那么必须提供一个install方法
// 那么必须在install方法中注册当前的这个组件
install: function (Vue, Options) {
// 1.根据我们的组件生成一个构造函数
let LoadingContructor = Vue.extend(Loading)
// 2.根据构造函数创建实例对象
let LoadingInstance = new LoadingContructor()
// 3.随便创建一个标签(元素)
let oDiv = document.createElement('div')
// 4.将创建好的标签添加到界面上
document.body.appendChild(oDiv)
// 5.将创建好的实例对象挂载到创建好的元素上
LoadingInstance.$mount(oDiv)
// 添加初始化值
if (Options && Options.title !== null && Options.title !== undefined) {
LoadingInstance.title = Options.title
}
// 添加全局方法
Vue.showLoading = function () {
LoadingInstance.isShow = true
}
Vue.hiddenLoading = function () {
LoadingInstance.isShow = false
}
// 添加实例方法
Vue.prototype.$showLoading = function () {
LoadingInstance.isShow = true
}
Vue.prototype.$hiddenLoading = function () {
LoadingInstance.isShow = false
}
}
}
5.在src目录的main.js中注册插件
import Loading from './plugin/loading/index'//加载组件
// 注意点: 如果想通过use的方式来注册组件, 那么必须先将组件封装成插件
Vue.use(Loading, {
title: '正在加载...'
})
6.如果想在发送网络请求的时候使用插件比如加载的组件,可以在自己定义的网络配置中添加请求拦截器和响应拦截器(详情可见以前的网络配置的文章)
let count = 0
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
count++
Vue.showLoading()//在插件的index.js中定义的方法 显示插件
return config
}, function (error) {
// 对请求错误做些什么
Vue.hiddenLoading()//在插件的index.js中定义的方法 隐藏插件
return Promise.reject(error)
})
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
count--
if (count === 0) {
Vue.hiddenLoading()//在插件的index.js中定义的方法 隐藏插件
}
return response
}, function (error) {
// 对响应错误做点什么
Vue.hiddenLoading()//在插件的index.js中定义的方法 隐藏插件
return Promise.reject(error)
})