vue 引入 ui 库时,会在 main.js 引入 类似这样的 use 以 vant 组件库为例
import Vant from 'vant';
Vue.use(Vant)
今天练习写一个 loading 的组件。
// 首先入口的 js 中引入自己写的公共插件的 js
import Vue from 'vue'
import { _utils } from '@/utils/utils.js'
Vue.use(_utils)
我使用 install 方法进行注入
// utils.js 所需私有方法集 这里可进行扩展组件
import { _loading } from '@/utils/privateTools'
const _utils = {}
// 挂载全局 _utils
_utils.install = function (Vue) {
_loading(Vue, function ($loading) {
Vue.prototype.$loading = {
show () {
$loading.isShow = true
},
hide () {
$loading.isShow = false
}
}
})
}
export {
_utils
}
接着 loading 引入模块
// privateTools
import LoadingPlugin from '@/plugins/common/Loading' // 引入 loading 模板
// 挂载
function _loading (Vue, cb) {
if (document.getElementsByClassName('loading_wrap').length) {
return
}
// 创建构造器
let LoadingTpl = Vue.extend(LoadingPlugin)
// 实例化loading
let $loading = new LoadingTpl()
// 插入DOM
document.body.appendChild($loading.$mount().$el)
cb($loading)
}
export {
_loading
}
最后 loading 模板
<template>
<div class="loading_wrap" v-show="isShow">
<!-- 图片 -->
<div class="loading_content"></div>
<!-- 文字 -->
<span>{{text}}</span>
</div>
</template>
<script>
/**
@class {props}
@param {Boolean} isShow 是否显示
@param {String} text 提示文字
*/
export default {
name: 'myLoading',
props: {
isShow: {
type: Boolean,
default: false
},
text: {
type: String,
default: '加载中...'
}
}
}
</script>
<style lang="scss" src="./index.scss" scoped></style>