封装组件,通过指令进行调用,类似于elementUI中的loading组件
step1:搭建组件
<template> <div v-show="show" class="comp_loading" :style="{background: background}"> <div class="loading_cont loading_fullscreen"> <SvgIcon icon-class="loading" class="loading_icon"></SvgIcon> </div> </div> </template> <script> import SvgIcon from '@/components/SvgIcon' export default { name: "loading", components:{ SvgIcon }, props:{ show : Boolean , background : String } } </script>
step2:在组件同级文件夹下创建index.js文件,作为组件调用配置
import Vue from 'vue' import LoadingComponent from './loading' let instance; const loadingConstructor = Vue.extend(LoadingComponent); instance = new loadingConstructor({ el:document.createElement('div') }); instance.show = false; const loading = { show(options){ instance.show = true; instance.background = options && options.background; document.body.appendChild(instance.$el); }, close(){ instance.show = false; } }; export default { install(options = {}){ if(!Vue.loading){ Vue.$loading = loading; } Vue.mixin({ created() { this.$loading = Vue.$loading; } }) } }
这里的设置实际上就是变相的利用install方法把loading指令挂载到页面上,这样全局都可以直接使用this.$loading进行调用 .
step3:全局挂载
在main.js中进行全局引用
import loading from './components/Loading' Vue.use(loading);
至此,就可以全局引用loading组件
this.$loading.show({background:'transparent'}); //调用loading 打开 background为其中配置样式,根据自己需求进行配置即可
this.$loading.close(); // 调用loading 关闭
封装element自带的loading
import Vue from 'vue' import { Loading } from 'element-ui' let loadingInstance = null const loading = { show(options) { loadingInstance = Loading.service({ text: '加载中', 'background': 'hsla(0,0%,100%,.7)' }) }, close() { if (loadingInstance) { loadingInstance.close() } } } export default { install(options = {}) { if (!Vue.loading) { Vue.$loading = loading } Vue.mixin({ created() { this.$loading = Vue.$loading } }) } }