Vue命令式弹窗组件如何实现?我很好奇😯😯😯__Vue.js
粉丝福利 : 关注VUE中文社区公众号,回复视频领取粉丝福利
前言
想必大家都用一些前端框架中诸如MessaBox或者Toast的组件,此类组件往往不需要我们显式的在使用组件的位置编写布局代码就能展示全局的弹框类组件。
this.$message.show(title,content);
你有没有好奇这个效果是怎么实现的呢,接下来我们就来实现一下类似的Loading加载中效果。
实现思路
- 创建一个
Loading.vue
文件编写布局 - 创建一个
Loading.js
文件并做下面👇几件事:- 使用
Vue.extend()
以Loading.vue
文件为template
创建一个新的Vue对象; - 把
Vue
对象挂在到一个新建的div标签上 - 将
div
标签添加到body
中。 - 使用
show()
和hide()
方法来控制组件的显示属性visible
- 使用
代码
Loading.vue
文件代码很简单,代码如下:
<template>
<transition name="loading" >
<div class="mask" @touchmove.stop.prevent v-show="visible">
<div class="showContent" >
<image src="../static/img/loading1.gif" class="loadingImg"></image>
<text class="lable">{{label}}</text>
</div>
</div>
</transition>
</template>
<script>
export default {
name:'loading',
data(){
return{
visible:false
}
},
props:{
type:{
},
label:{
default:"加载中...",
type:String
}
}
}
</script>
<style>
.mask{
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}
.showContent{
width: 160px;
height: 160px;
display: flex;
justify-content: center;
align-items: center;
padding: 10px;
}
.loadingImg{
width: 70px;
height: 70px;
}
.lable{
font-size: 28px;
color: #ffffff;
margin-top: 15px;
}
/*过渡效果*/
.loading-enter,
.loading-leave-active {
transition: opacity .3s linear;
opacity: 0 ;
}
</style>
此vue文件主要做了哪些事情呢?
-
根布局fixed定位覆盖整个界面;
-
在根布局上添加
@touchmove.stop.prevent
屏蔽事件向下传递 -
使用
visible
控制组件显示 -
添加组件消失时的过渡效果
Loading.js
代码如下,详细实现都在注释中说明了。
//引入vue组件
import temp from '../components/loading'
import Vue from 'vue';
//创建Vue对象
const loading=Vue.extend(temp);
let instance;
export default{
show(options={}){
if (!instance) {
//创建div标签并挂载Vue对象
instance=new loading({
el:document.createElement('div')
})
}
if (instance.visible) return;
instance.label = typeof options === 'string' ? options : options.text || '';
instance.type = options.type || 'nomal';
//将新创建的div添加到body中去
document.body.appendChild(instance.$el);
Vue.nextTick(() => {
//修改组件的visible属性控制显示和隐藏
instance.visible = true;
});
},
hide(){
if (instance) {
/*因为加载中往往伴随着界面的数据变化和更新,因此需要在nextTick中执行,
即在数据真正驱动界面变化之后再关闭加载中弹窗*/
Vue.nextTick(() => {
instance.visible = false;
});
}
}
}
使用Loading组件
improt Loading from "./Loading.js"
Loading.show();
setTimeout(()=>{
Loading.hide();
},1000)
如需在vue中全局使用那么可以这样做
//main.js
improt Loading from "./Loading.js"
Vue.prototype.$loading=Loading;
//需要使用的地方
this.$loading.show();
setTimeout(()=>{
this.$loading.hide();
},1000)
最终的运行效果如下图:
版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 作者: 一拳小和尚 原文链接:https://juejin.im/post/6844904104167243789