弹窗插件

329 阅读1分钟

uniapp选择使用vue.js作为开发框架,那么我们一定要利用上vue中的一些优秀特性,例如插件(plugin),关于vue插件的介绍大家可以直接去官网看。

vue 插件官方介绍链接

通过引入插件,我们可以极大的提升我们的开发效率,当然如果是第一次使用uniapp进行开发可能不清楚哪个功能适合封装成插件引入,下面我就介绍一下一些我在实际开发中封装的一些通用插件

在封装前我们需要写一个 config 文件,方便我们快速自定义一些颜色和请求路径等。

//congif.js
const config = {
	baseUrl:'https://example.cn',//请求的基本路径
	modalColor:'#5271FF', //弹窗颜色 
}

module.exports = config

在小程序中,如果我们没有自定义弹窗和拟态框组件的话一般都是使用官方的showModal或者showToast api来进行一些用户交互。这种非常频繁使用到的操作非常适合封装起来快速调用。具体代码如下

插件代码

const config = require('../config.js')

var message = {
	toast(title, type = 'text') {
		if (title.length > 15) {
			console.error('toast长度超过15个字符,当前长度为' + title.length)
			return
		}
		var icon = 'none'
		if (type) {
			switch (type) {
				case 'text':
					icon = 'none'
					break
				case 'suc':
					icon = 'success'
					break
				case 'err':
					icon = 'error'
					break
			}
		}
		uni.showToast({
			title,
			icon
		})
	},
	confirm(title, confirmColor) {
		return new Promise((res, rej) => {
			uni.showModal({
				title,
				cancelColor: '#b6b6b6',
				confirmColor: confirmColor || config.modalColor,
				success: (result) => {
					if (result.cancel) {
						rej(result)
					} else if (result.confirm) {
						res(result)
					}
				}

			})
		})
	},
	async message(content, confrimText) {
		return new Promise((res) => {
			uni.showModal({
				title: '提示',
				content,
				showCancel: false,
				confirmColor: config.modalColor,
				success: (result) => {
					res(result)
				}
			})
		})
	}
}
module.exports = message