手动挂载组件-demo
2020-09-18 本文已影响0人
冰滩波纹
- 官方文档:https://cn.vuejs.org/v2/api/#vm-mount
- 仿写
elementUI
的this.$message
。
MyNotice/MyNotice.vue
<template>
<div class="notice-box">
<div class="message"
:class="item.type"
v-for="item in msgList"
:key="item._name"
>
<div class="content">{{item.content}}</div>
</div>
</div>
</template>
<script>
const DefaultOption = {
duration: 1500,
type: "normal",
content: "提示内容!",
};
let idx = 0;
export default {
data() {
return {
msgList: [],
};
},
methods: {
add(msgOpt = {}) {
// name标识 用于移除弹窗
let _name = this.getName();
// 并入默认配置,并赋值
msgOpt = Object.assign(
{
_name,
},
DefaultOption,
msgOpt
);
this.msgList.push(msgOpt);
setTimeout(() => {
this.removeMsg(_name);
}, msgOpt.duration);
},
getName() {
return "msg_" + idx++;
},
removeMsg(_name) {
let index = this.msgList.findIndex((item) => item._name === _name);
this.msgList.splice(index, 1);
},
},
};
</script>
<style lang='scss' scoped>
.notice-box {
position: fixed;
top: 50px;
left: 50%;
display: flex;
flex-direction: column;
align-items: center;
transform: translateX(-50%);
.message {
border-width: 3px;
min-width: 240px;
max-width: 500px;
margin-bottom: 10px;
border-radius: 3px;
box-shadow: 0 0 8px #ddd;
overflow: hidden;
&.normal {
border-left: 3px solid #909399;
background: #f4f4f5;
}
&.success {
border-left: 3px solid #67c23a;
background: #f0f9eb;
}
&.error {
border-left: 3px solid #f56c6c;
background: #fef0f0;
}
&.warning {
border-left: 3px solid #e6a23c;
background: #fdf6ec;
}
.content {
padding: 8px;
line-height: 1.3;
}
}
}
</style>
MyNotice/index.js
import Vue from 'vue'
import MyNotice from './MyNotice.vue'
let noticInstance = null,
NoticeConstructor = Vue.extend(MyNotice),
init = () => {
noticInstance = new NoticeConstructor()
noticInstance.$mount()
document.body.appendChild(noticInstance.$el)
},
caller = (opt) => {
if (!noticInstance) {
init()
}
noticInstance.add(opt)
}
export default {
// 返回 install 函数 用于 Vue.use 注册
install(vue) {
vue.prototype.$notice = caller
},
}
main.js
import MyNotice from '@/components/MyNotice/index.js'
Vue.use(MyNotice)
- 调用
myNotice() {
this.$notice({
type: "success",
content: "成功信息提示",
duration: 2000,
})
}