|
@@ -0,0 +1,70 @@
|
|
|
+import { reactive, h } from 'vue'
|
|
|
+import PtcToast from './Toast.vue'
|
|
|
+import { mountComponent } from '../utils/mount-component'
|
|
|
+
|
|
|
+interface ToastProps {
|
|
|
+ visible: boolean
|
|
|
+ message: string
|
|
|
+ duration?: number
|
|
|
+ icon?: 'loading' | 'none'
|
|
|
+}
|
|
|
+
|
|
|
+type ToastOptions = Omit<ToastProps, 'visible'>
|
|
|
+
|
|
|
+interface ToastExposed {
|
|
|
+ open(options: ToastOptions): void
|
|
|
+ close(): void
|
|
|
+}
|
|
|
+
|
|
|
+const defaultOptions: Partial<ToastOptions> = {
|
|
|
+ duration: 2000,
|
|
|
+ icon: 'none',
|
|
|
+}
|
|
|
+
|
|
|
+let instance: ToastExposed | undefined
|
|
|
+
|
|
|
+function getInstance() {
|
|
|
+ if (!instance) {
|
|
|
+ instance = mountComponent<ToastExposed>({
|
|
|
+ setup(props, { expose }) {
|
|
|
+ const state = reactive<ToastProps>({ visible: false, message: '' })
|
|
|
+ const attrs = {
|
|
|
+ 'onUpdate:visible': (v: boolean) => {
|
|
|
+ state.visible = v
|
|
|
+ v || document.body.classList.remove('lock')
|
|
|
+ },
|
|
|
+ }
|
|
|
+ const open = (options: ToastOptions) => {
|
|
|
+ state.visible = true
|
|
|
+ Object.assign(state, { ...defaultOptions, ...options })
|
|
|
+ }
|
|
|
+ const close = () => {
|
|
|
+ state.visible = false
|
|
|
+ }
|
|
|
+ expose({ open, close })
|
|
|
+
|
|
|
+ return () => h(PtcToast, { ...state, ...attrs })
|
|
|
+ },
|
|
|
+ }).instance
|
|
|
+ }
|
|
|
+ return instance
|
|
|
+}
|
|
|
+
|
|
|
+export default function Toast(options: string | ToastOptions) {
|
|
|
+ if (typeof options === 'string') options = { message: options }
|
|
|
+ const toast = getInstance()
|
|
|
+ toast.open(options)
|
|
|
+ options.icon === 'loading'
|
|
|
+ ? document.body.classList.add('lock')
|
|
|
+ : document.body.classList.remove('lock')
|
|
|
+ return toast
|
|
|
+}
|
|
|
+
|
|
|
+Toast.loading = (message = '加载中...') =>
|
|
|
+ Toast({ message, duration: 0, icon: 'loading' })
|
|
|
+Toast.hide = () => {
|
|
|
+ instance?.close()
|
|
|
+}
|
|
|
+
|
|
|
+const win: any = window
|
|
|
+win.Toast = Toast
|