增加自动消失功能
func-notification.js
mounted () {
this.createTimer()
},
methods: {
createTimer () {
if (this.autoClose) {
this.timer = setTimeout(() => {
this.visible = false
}, this.autoClose)
}
},
clearTimer () {
if (this.timer) {
clearTimeout(this.timer)
}
}
},
beforeDestory () {
this.clearTimer()
},
data () {
return {
verticalOffset: 0,
autoClose: 3000,
visible: false
}
}
notification.vue 默认为显示
<div class="notification" :style="style" v-show="visible">...</div>
data () {
return {
visible: true
}
}
function.js:autoClose可自定义传
const notify = (options) => {
const {
autoClose,
...rest
} = options
// 利用解构
const instance = new NotificationConstructor({
propsData: {
...rest
},
data: {
autoClose: autoClose === undefined ? 3000 : autoClose //避免没有传autoClose没有值
}
})
}
增加删除dom和vm对象操作
notification.vue中
//transition上增加 动画结束后再触发
@after-leave="afterLeave"
methods: {
afterLeave () {
this.$emit('closed')//派发事件
}
}
function.js
const removeInstance = (instance) => {
if (!instance) return
const index = instances.findIndex(inst => instance.id === inst.id)
instances.splice(index, 1)
}
const notify = (options) => {
...
instance.vm.$on('closed', () => {
removeInstance(instance)
document.body.removeChild(instance.vm.$el)
instance.vm.$destroy()
})
}
增加点击关闭删除dom和vm对象操作
const notify = (options) => {
...
instance.vm.$on('close', () => {
instance.vm.visible = false
})
}
增加删除后重新计算位置
notification.vue
//transition上增加 显示的时候才能获取到高度
@after-enter="afterEnter"
methods: {
afterEnter () {}
}
func-notification.js
methods: {
afterEnter () {
this.height = this.$el.offsetHeight //计算出当前节点高度
}
},
data () {
return {
...
height: 0,visible: false //visible: false让组件触发afterEnter
}
}
function.js : 完善removeInstance
const removeInstance = (instance) => {
if (!instance) return
const len = instances.length
const index = instances.findIndex(inst => instance.id === inst.id)
instances.splice(index, 1)
if (len <= 1) return
const removeHeight = instance.vm.height
for (let i = index; i < len - 1; i++) {
instances[i].verticalOffset = parseInt(instances[i].verticalOffset) - removeHeight - 16
}
}
const notify = (options) => {
...
// 插入节点后再显示
document.body.appendChild(instance.vm.$el)
instance.vm.visible = true
}
鼠标聚焦不关闭,移出重新开始自动消失
notification.vue
<div class="notification" @mouseenter="clearTimer" @mouseleave="createTimer"></div>
methods: {
clearTimer () {},//func-notification.js覆盖了方法
createTimer () {}
}