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()
})
不知道有没有更好的方法,如果以后有就再来添加。