telport的使用
- telport传送门,把你的组件代码传送到你设定id的组件上。首先先创建一个toast的结构。
<template>
<teleport to="#toast">
<div class="alert text-center w-50 fixed-bottom mb-5 mx-auto" v-if="isVisible" :class="classObject">
{{message}}
</div>
</teleport>
</template>
设定三种状态
export type ToastType = 'success' | 'error' | 'default';
传入的参数有:
props: {
message: String,
type: {
type: String as PropType<ToastType>,
default: 'default'
}
},
- 编写代码,在setup的时候把模块添加到telport的id为toast的组件上,并且在unmount的时候移除。
import {onUnmounted} from 'vue'
const userCreateDom = (nodeId: string) => {
const node = document.createElement('div')
node.id = nodeId;
document.body.appendChild(node)
onUnmounted(() => {
document.body.removeChild(node)
})
}
export default userCreateDom
- 创建createToast.ts文件,实现创建toast和移除
import {createApp, PropType} from 'vue'
import Toast, {ToastType} from '../components/Toast.vue'
const createToast = (message: string, type: ToastType='default', dismiss?: () => void, timeout: number=2000) => {
const toast = createApp(Toast, {
message,
type
})
const mountNode = document.createElement('div')
document.body.appendChild(mountNode)
toast.mount(mountNode)
setTimeout(() => {
toast.unmount(mountNode)
document.body.removeChild(mountNode)
if (dismiss) {
dismiss()
}
}, timeout)
}
export default createToast;
- 调用
const onTap = () => {
createToast('测试弹框', 'success')
}