Vue 通过prototype添加全局属性/方法

通过prototype定义Vue实例的原型属性,使每个Vue实例中都可以用,又不会污染全局作用域。
toast.js

const Toast = {
	//设置缓存(expire为缓存时效)
	show(title, icon = 'none', duration = 1500) {
		uni.showToast({
			title: title || '',
			icon: icon,
			duration: duration
		})
	},
	showLoading(title) {
		uni.showLoading({
			title: title || ''
		})
	},
	hideLoading() {
		uni.hideLoading()
	}
}

export default Toast;

main.js

import toast from 'utils/toast.js'

Vue.prototype$toast = toast

使用时通过this.$toast可以直接取出该toast对象

this.$toast.showLoading()
this.$toast.hideLoading()

如果不想每次都输$可以通过

//注册
Vue.prototype['toast'] = toast
//访问的时候
this.toast.showLoading()
this.toast.hideLoading()
posted @   qqcc1388  阅读(841)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
历史上的今天:
2018-04-26 iOS 获取LaunchImage启动图
2017-04-26 一个简单的算法 - 将一个正整数拆分成指定几个正整数的组合
点击右上角即可分享
微信分享提示