Vue中如何开发纯Api弹框?

143 阅读2分钟

图片

在我们前端封装一个弹框UI组件时,原理非常简单,就是一个UI组件, 组件封装=> 页面import引入=>页面模版放置=> 通过调用组件内部弹框提示打开方法

但是我们在用Uniapp 框架中内置自带

uni.showLoading()  uni.showToast()  uni.showModal() 这些JS方法,我们调用这个JS方法就可以在页面中出现弹框类型的节点,

**这是怎么开发的? 他不需要引入什么UI组件, 不需要什么模版放置组件, 直接调用全局APi就可以了
**

用调用JS方法,在页面中展示弹框节点展示, 本质原理就是 

在调用的方法是向页面中添加了一个Dom节点,节点的出现/消失 底层原理就用appendChild removeChild 方法

我们可以这样做=>1 把冰箱门打开 2把大象放进去 3 把冰箱门关上 图片

1:新建一个 vue页面 toast.vue

<template>
	<view className="toast" v-show="show">{{msg}}</view>
</template>

<script>
	export default {
		data() {
			return {
				show: true,
				msg: ''
			};
		},
		methods: {
			//刚方法就是调用JS挂载弹框的显示方法
			shows(msg) {
				this.msg = msg;
				this.show = true;
			},
			hide() {
				this.show = false;
			}
		}
	};
</script>

<style lang="scss" scoped>
	.toast {
		width: 200rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		color: #fff;
		background: #999999;
		border-radius: 20rpx;
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}
</style> 

这个页面就是我们调用JS方法时,页面中显示的页面, 

那怎么用JS方法把界面与方法衔接起来呢?

关键点来了!

2:我们再新建一个 toast.js

因为在Vue中所有单独显示的dom节点都是一个vue的子组件并且都继承vue,

import toast from './toast.vue'; // 引入弹框页面

import Vue from 'vue';
// 重点 因为模版组件继承Vue,返回该组件构造函数
const Toast = Vue.extend(toast);

export function showToast(masg) { //对外暴漏改方法
	//重点 new出该组件 实例
	const toastCopm = new Toast().$mount();
	//重点 将组件实例 下的 $el (类型:Dom节点) 属性放到 document里
	document.body.appendChild(toastCopm.$el);

	// 调用弹框显示方法
	toastCopm.shows(masg);
	let time;
	clearInterval(time)
	time = setTimeout(() => {
		// 调用弹框隐藏方法
		toastCopm.hide();
		//重点 移除弹框挂载
		toastCopm.$el.parentNode.removeChild(toastCopm.$el);
	}, 1000);
}

3:在main.js引入toast中方法。并挂载全局

import App from './App'
import Vue from 'vue';
//引入我们toast.js
import {
   showToast
} from './pages/toast/toast.js'
//将方法挂载全局
Vue.prototype.$showToast = showToast;

Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
   ...App
})
app.$mount()

ok 大功告成! 是不是很简单学会这个 图片

onShow() { //在页面中生命周期调用该方法    this.$showToast('阿勇最帅');},

显示结果 图片

mp.weixin.qq.com/s?__biz=Mzk… 微信扫一扫
关注该公众号

关注微信公众号 阿勇学前端,

转发分享文章,每天分享前端有趣好玩的东西