Vue命令式弹窗组件如何实现?我很好奇??????
2020/3/27 11:31:17
本文主要是介绍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 || 'snake'; //将新创建的div添加到body中去 document.body.appendChild(instance.$el); Vue.nextTick(() => { //修改组件的visible属性控制显示和隐藏 instance.visible = true; }); }, hide(){ if (instance) { /*因为加载中往往伴随着界面的数据变化和更新,因此需要在nextTick中执行, 即在数据真正驱动界面变化之后再关闭加载中弹窗*/ Vue.nextTick(() => { instance.$data.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) 复制代码
最终的运行效果如下图:
这篇关于Vue命令式弹窗组件如何实现?我很好奇??????的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04package.json 文件位置在哪?-icode9专业技术文章分享
- 2024-10-01Craco.js学习:从入门到实践指南
- 2024-10-01Create-React-App学习:入门与实践指南
- 2024-10-01CSS-in-JS学习:从入门到实践指南
- 2024-09-30JSX语法学习:从入门到初步掌握
- 2024-09-30Mock.js学习:入门教程与实战演练
- 2024-09-30React Hooks学习:从入门到实践
- 2024-09-30受控组件学习:React中的基础入门教程
- 2024-09-29JS定时器教程:初学者必看指南
- 2024-09-29JS对象教程:初学者的全面指南