页面展示
代码
@/components/GlobalDialog/index.vue
<template>
<div class="global_dialog" v-if="isVisible">
<div class="global_dialog_header">
<div class="global_dialog_header_title">{{ title }}</div>
<i class="el-icon-close" @click="closeDialog" />
</div>
<div class="global_dialog_slot">
<slot></slot>
</div>
</div>
</template>
<script>
export default {
name: 'GlobalDialog',
props: {
isVisible: {
type: Boolean,
default: false
},
title: {
type: String,
default: ''
}
},
methods: {
closeDialog() {
this.$emit('close')
}
}
}
</script>
<style scoped lang="scss">
.global_dialog {
max-width: 20vw;
padding: 20px;
position: fixed;
right: 10px;
bottom: 10px;
z-index: 999;
box-shadow: 0 0 3px 3px #ccc;
border-radius: 5px;
background-color: #fff;
&_header {
margin-bottom: 10px;
display: flex;
justify-content: space-between;
font-size: 16px;
&_title {
margin-right: 20px;
font-weight: bold;
}
.el-icon-close {
cursor: pointer;
}
}
&_slot {
white-space: pre;
line-height: 25px;
}
}
</style>
@/plugins/global-dialog.js
import GlobalDialog from '@/components/GlobalDialog'
export default {
install(Vue, options) {
// 创建一个新的Vue实例作为全局弹框
const ModalConstructor = Vue.extend(GlobalDialog)
let modalInstance = new ModalConstructor({
el: document.createElement('div'),
propsData: {
isVisible: false
}
})
// 添加方法来显示弹框
Vue.prototype.$showGlobalDialog = (content, props) => {
modalInstance.isVisible = true
Object.keys(props).forEach((key) => {
modalInstance[key] = props[key]
})
modalInstance.$slots.default = [content] // 插入内容
document.body.appendChild(modalInstance.$el)
}
Vue.prototype.$hideGlobalDialog = () => {
modalInstance.isVisible = false
}
// 监听关闭事件来隐藏弹框
modalInstance.$on('close', () => {
modalInstance.isVisible = false
})
}
}
main/js
import Vue from 'vue'
import App from './App.vue'
import router from './router/index'
import store from './store/index'
// ...
import GlobalDialog from './plugins/global-dialog.js' // 【主要代码】
Vue.use(GlobalDialog); // 【主要代码】
router.beforeEach((to, from, next) => {
/** ** 作为子系统处理 start ****/
if (to.path === '/login') {
// 进入登陆页关闭全局弹框
Vue.prototype.$hideGlobalDialog() // 【主要代码】
}
})
new Vue({
router,
store,
render: (h) => h(App)
}).$mount('#app')
使用全局组件
this.$showGlobalDialog(
`待办预警:${res.data.superviseTaskCount || 0} 条\n待办巡查:${res.data.patrolTaskCount || 0} 条`,
{title: '待办提醒'}
)