需要形容
本文咱们应用vue的extend办法实现一个全屏loading加载成果,需要如下:
- 通过命令就能够让弹框开启或敞开,比方
this.$showDialog()
开启,this.$hideDialog()
敞开 - 办法能够传参更改loading中的文字
- 也能够传参更改loading背景色
当然这里除了文字,背景色什么的,也能够传递更多的参数,具体能够依据业务场景设计,为了便于了解文章这里就不赘述了。
咱们先看一下效果图:
效果图
代码实现
第一步,新建loading组件
比方咱们在src目录下,新建loading文件夹用于寄存loading相干文件,在这个文件夹下新建的loading.vue文件是用来做弹出框的组件
src/loading/loading.vue
<template>
<!-- 关上弹框的动画 -->
<transition name="animation">
<div
class="loadindWrap"
v-if="showLoading"
:style="{ background: backgroundColor }"
>
<div class="loadingContent">
<div class="iBox">
<i class="el-icon-loading"></i>
</div>
<div class="text">{{ text }}</div>
</div>
</div>
</transition>
</template>
<script>
export default {
data() {
return {
showLoading: false, // 管制显示与暗藏的标识
backgroundColor: "rgba(0, 0, 0, 0.5)", // 默认背景色
text: "加载中...", // 默认文字
};
},
};
</script>
<style lang="less" scoped>
.loadindWrap {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
.loadingContent {
color: rgb(160, 233, 66);
text-align: center;
.iBox {
margin-bottom: 6px;
i {
font-size: 20px;
color: #bfa;
}
}
}
}
// 加一个过渡成果
.animation-enter, .animation-leave-to { opacity: 0;}
.animation-enter-active, .animation-leave-active { transition: opacity 0.6s; }
</style>
第二步,新建index.js文件
比方咱们在src目录下,新建的loading文件夹中再新建一个index.js文件用来书写相应js代码,用于管制loading弹框。
src/loading/index.js
// 引入vue
import Vue from 'vue'
// 引入loading组件
import dialog from './loading';
// 通过Vue的extend办法继承这个引入的dialog组件,继承后会返回一个vue子类,须要应用实例化即可
const Dialog = Vue.extend(dialog);
//创立实例并且挂载到一个div上
const app = new Dialog().$mount(document.createElement('div'))
// 关上弹框函数
function showDialog(options) {
//初始化调用传递过去的参数赋值更改组件内外部值
for (let key in options) {
app[key] = options[key];
}
// 让其显示
app.showLoading = true
// 并将其插入body中
document.body.appendChild(app.$el);
}
// 敞开弹框函数
function hideDialog() {
// 因为是v-if去管制,所以将标识showLoading置为false,就会主动把弹框dom删掉
app.showLoading = false
}
// 将关上函数和敞开函数都挂载到Vue原型上,不便咱们调用
Vue.prototype.$showDialog = showDialog;
Vue.prototype.$hideDialog = hideDialog;
第三步,在main.js中引入之
main.js
// ...
// 最初要在main.js中引入,示意应用之,这样在任意组件中都是执行对应办法了
import './loading/index.js'
new Vue({
render: h => h(App),
router,
store // 挂载下来
}).$mount('#app')
第四步,命令式调用
在须要应用的组件中应用
<template>
<div class="aBox">
<el-button @click="show">点击呈现加载中弹框</el-button>
</div>
</template>
<script>
export default {
methods: {
// 通过指令的形式即可调用,很不便
show() {
this.$showDialog({
text: "浏览器在加载中哇...",
});
// 模仿发申请,过了1.5秒钟再将其敞开
setTimeout(() => {
this.$hideDialog();
}, 1500);
},
},
};
</script>
Vue.extend办法的了解
咱们晓得,无论哪种程序语言,或多或少都会有封装、继承、多态的思维,而Vue.extend办法就是Vue的一个用于继承组件的办法。官网是这样定义的:应用根底 Vue 结构器,创立一个“子类”。参数是一个蕴含组件选项的对象。
结构器也能够了解为是一个类,既然是一个类,就能够去实例化对象,extend办法能够实例一个组件对象,而这个组件对象领有咱们最后定义的loading.vue所有属性和办法。所以咱们将这个组件对象挂载到一个div上,让其有一个着落,即成为dom元素。
最终,当咱们须要弹框呈现的时候,把这个dom元素插入到文档对象上,不须要的时候,再将其删除掉。这样就实现了,关上和敞开弹框的成果。
❤ thanks reading ❤
发表回复