Vue自定义全局Toast和Loading的实例详解
如果我们的Vue项目中没有用到任何UI框架的话,为了更好的用户体验,肯定会用到loading和toast。那么我们就自定义这两个组件吧。
1、Toast组件
首先,在common下新建global文件夹,存放我们的toast.vue和toast.js两个文件(当然文件的具体位置你可以自行安排)。
(1).toast.vue
{content}
(2).toast.js
importVuefrom'Vue'
importToastComponentfrom'./Toast.vue'
constToast={}
letshowToast=false//存储loading显示状态
lettoastNode=null//存储loading节点元素
constToastConstructor=Vue.extend(ToastComponent)
Toast.install=function(Vue,options){
//参数
varopt={
duration:'1200'
}
for(varpropertyinoptions){
opt[property]=options[property]
}
Vue.prototype.$toast=function(tips,type){
if(type==='hide'){
toastNode.isShowToast=showToast=false
}else{
if(showToast){
//如果toast还在,则不再执行
return
}
toastNode=newToastConstructor({
data:{
isShowToast:showToast,
content:tips
}
})
toastNode.$mount()//挂在实例,为了获取下面的toastNode.$el
document.body.appendChild(toastNode.$el)
toastNode.isShowToast=showToast=true
setTimeout(function(){
toastNode.isShowToast=showToast=false
},opt.duration)
}
};
['show','hide'].forEach(function(type){
Vue.prototype.$toast[type]=function(tips){
returnVue.prototype.$toast(tips,type)
}
})
}
exportdefaultToast
然后,我们需要把写好的组件在/src/main.js中引用一下。
importToastfrom'./components/common/global/toast' Vue.use(Toast)
最后,怎么使用呢?只需在要用的地方this.$toast.show('helloworld')
2、Loading组件
loading组件只需要照着toast组件搬过来,稍微改下就可以了。
首先,在common下新建global文件夹,存放我们的loading.vue和loading.js两个文件。
(1).loading.vue
{content}