Vue构造函数

Vue.extend(options)官网实例:

<div id="mount-point"></div>
// 创建构造器
var Profile = Vue.extend({
  template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
  data: function () {
    return {
      firstName: 'Walter',
      lastName: 'White',
      alias: 'Heisenberg'
    }
  }
})
// 创建 Profile 实例,并挂载到一个元素上。
new Profile().$mount('#mount-point')

利用Vue构造函数,模仿vantUI封装Toast轻提示。
toast.js

const NoticeConstructor = Vue.extend(require("./toast.vue").default)
const NoticeInstance = new NoticeConstructor()
let nId =1
let box = document.createElement('div')
box.id ='toastBox'
document.body.appendChild(box)

const Toast = (options) =>{
	let id = 'message-'+nid++
	options =options ||{}
	if(typeof options === 'string'){
		options = {
			message: options
		}
	}
	NoticeInstance.id = id
	NoticeInstance.vm = NoticeInstance.$mount()
	NoticeInstance.vm.isShow = true//修改组件的值
	NoticeInstance.vm.type= options.type//修改组件的值
	
	NoticeInstance.dom = NoticeInstance.vm.$el
	box.appendChild(NoticeInstance.dom)
	NoticeInstance.dom.style.zIndex = nId +1001
	
	return NoticeInstance.vm
}
//四种提示(2s后自动关闭)
['success','warning','info','error'].forEach(e=>{
	Toast[e] = (options)=>{
		if(typeof options ==='string'){
			options = {
				message: options
			}
		}
		options.type = e
		setTimeout(()=>{
			NoticeInstance.isShow = false
		},options.duration||2000)
		return Toast(options)
	}
})
//loading提示框(不能自动关闭,只可手动关闭)
Toast.loading = (options)=>{
	if(typeof options ==='string'){
		options = {
			message: options
		}
	}
	options.type = 'loading'
	return Toast(options)
}
//手动关闭提示框
Toast.close = ()=>{
	NoticeInstance.isShow = false
}

export default Toast

封装的Toast轻提示全局引入调用
vue项目的入口文档main.js

//引入
import Toast from './toast.js'
Vue.prototype.$toast = Toast 
//调用
this.$toast.loading({
	message:'提示内容'
})
this.$toast.success({
	message:'提示内容'
})

但是这样还是有个问题,就是:如果使用了不自动关闭的toast,页面切换toast不关闭,所以我在router中做了导航守卫:
router.js

router.beforeEach((to,from,next)=>{
	let toastBox = document.getElementById('toastBox')
	toastBox.innerHTML =''
	next()
})

不知道有没有更好的方法,如果以后有就再来添加。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值