<template>
<transition name="fade" @after-leave="afterLeaveFn" @after-enter="afterEnterFn">
<div class="message"
:style="style"
v-show="isShow"
@mouseenter="emptyTimeFn"
@mouseleave="clearTimeFn"
>
<p>{{content}}</p>
<button @click="ClickCloceFn">{{btn}}</button>
</div>
</transition>
</template>
<script>
export default {
name: 'message',
props:{
content: {
type: String,
required:true
},
btn: {
type: String,
default: '关闭'
}
},
computed:{
style () {
return {}
}
},
data () {
return {
isShow: false,
height:0,
}
},
methods: {
},
}
</script>
<style scoped lang="scss">
.fade-enter-active, .fade-leave-active {
transition: opacity .5s
}
.fade-enter, .fade-leave-active {
opacity: 0
}
.message{
width: 200px;
background: rgb(0,0,0,0.5);
border-radius: 5%;
p{
color: #ffffff;
padding: 0 10px;
box-sizing: border-box;
}
button{
position: absolute;
top: 0;
right: 0;
}
}
</style>
- 使用基础 Vue 构造器,创建一个“子类”。 extends扩展
import message from "./message";
export default {
extends: message,
computed:{
style () {
return {
position: 'fixed',
top: `${this.offsetHeight}px`,
right: '20px'
}
}
},
data () {
return {
offsetHeight: 0,
autoClear: 0,
}
},
methods: {
clearTimeFn () {
if(this.autoClear){
this.time = setTimeout(()=>{
this.isShow = false
},this.autoClear)
}
},
emptyTimeFn () {
if(this.time){
clearTimeout(this.time)
}
},
ClickCloceFn () {
this.$emit('cloceFn')
},
afterLeaveFn () {
this.$emit('afterLeaveFn')
},
afterEnterFn () {
this.height = this.$el.offsetHeight
}
},
mounted(){
this.clearTimeFn()
this.isShow = true
},
beforeDestroy() {
console.log('已销毁')
this.emptyTimeFn()
}
}
- 通过方法实现动态挂载DOM(可以写你想做的一切事情)
import Vue from "vue";
import Component from './Fn_index'
const newComponent = Vue.extend(Component)
const instanceArr = [];
let seed = 1;
const removeFn = (el)=>{
console.log(el)
if(!el) return;
let idx = instanceArr.findIndex(item => el.id === item.id)
instanceArr.splice(idx,1);
const len = instanceArr.length;
console.log(len)
if(len <=0) return;
const H = el.vm.height + 20;
for (let i=idx; i<len; i++){
instanceArr[i].offsetHeight = instanceArr[i].offsetHeight - H
}
};
const messageFn = (options) => {
if(Vue.prototype.$isServer) return;
const instance = new newComponent({
propsData: options,
data: {
autoClear:options.autoClear?autoClear:3000
}
});
let id = `messagetions_${seed++}`;
instance.id = id;
instance.vm = instance.$mount();
document.body.appendChild(instance.vm.$el);
let heightOffset = 0;
instanceArr.forEach((item,idx)=>{
heightOffset += item.$el.offsetHeight + 20;
});
heightOffset += 20;
instance.$data.offsetHeight = heightOffset;
instanceArr.push(instance);
instance.vm.$on('cloceFn',()=>{
console.log('cloceFn')
instance.vm.isShow = false
});
instance.vm.$on('afterLeaveFn',()=>{
console.log('afterLeaveFn')
removeFn(instance)
document.body.removeChild(instance.vm.$el);
instance.vm.$destroy()
});
return instance.vm
};
export default messageFn