概要
vuetify 没有全局函数命令组件 故 根据 snackbar 组件 二次封装 VFNotification 全局使用
现在存在的问题:
- 因为需要重新挂载vuetify 组件库,所以一开始初始化vuetify组件时配置的主题 需要重新配置 不然会影响全局的主题色配置,其他的配置项不变
- 使用时在.vue 文件使用 setup语法糖 时 不能在 vuetify 所有的方法实例前面使用 因为 这里没有配置 其他的配置项,只能在后面使用不然报错;
- 多次调用 显示的位置不变
因时间有限制,项目着急,后续将优化这些问题.。 有时间的你们也可以优化一下哈!!
引入vuetify组件
import { createApp } from 'vue'
import { createVuetify } from 'vuetify'
import * as components from 'vuetify/components'
MessageBox
// 这是JSX语法 所以 文件夹命名也是 jsx 别忘记了
const MessageBox = {
props: {
message: {
type: String,
default: '',
},
snackbar: {
type: Boolean,
default: true,
},
type: {
type: String,
default: 'info',
},
position: {
type: String,
default: 'top',
},
timeout: {
type: Number,
default: 5000,
},
positionStyle: {
type: String,
default: 'top: 0px',
},
showClose: {
type: Boolean,
default: false,
},
},
render(ctx) {
const { $props, $attrs, $emit } = ctx
const messageType = () => {
const colorType = {
info: {
bg: '#FAFAFA',
color: '#BDBDBD',
icon: 'mdi-information',
},
success: {
bg: '#E8F5E9',
color: '#66BB6A',
icon: 'mdi-check-circle',
},
warning: {
bg: '#FFF3E0',
color: '#FFA726',
icon: 'mdi-alert-circle',
},
error: {
bg: '#FFEBEE',
color: '#EF5350',
icon: 'mdi-close-circle',
},
}
return colorType[$props.type] || '#e9e9eb'
}
return (
<v-snackbar v-model={$props.snackbar} style={$props.positionStyle} location={$props.position} timeout={$props.timeout} color={messageType().bg}>
{{
text: () => (
<p style={`display: flex; align-items: flex-end; color: ${messageType().color}`}>
<v-icon icon={messageType().icon} class="mr-2" />
{$props.message}
</p>
),
actions: () => ($props.showClose ? <v-icon icon="mdi-close" color="#BDBDBD" /> : ''),
}}
</v-snackbar>
)
},
}
导出VFNotification
const vuetify = createVuetify({
components,
theme: {
themes: {
light: {
colors: {
primary: '#111111',
secondary: '#4DB6AC',
},
},
dark: {
colors: {
primary: '#EEEEEE',
secondary: '#FAFAFA',
},
},
},
},
})
/**
* @param { Object } options // 配置项
*/
var timeId
export default function VFNotification(options) {
const app = createApp(MessageBox, {
...options,
onClick() {
if (options.showClose) {
app.unmount()
div.remove()
}
},
})
const div = document.createElement('div')
document.body.appendChild(div)
app.use(vuetify)
app.mount(div)
const { timeout } = options || {}
timeId = setTimeout(() => {
app.unmount()
div.remove()
}, timeout || 3000)
}
使用示例
/**
* 使用示例 - 参数只支持对象
*
*/
import VFNotification from '@/utils/VFNotification'
VFNotification({
message: 'xxxx消息',
type: 'error',
showClose: true, // 开启支持点击关闭
position: 'top right',
positionStyle: 'top: 60px', // 定位样式
})