1、vue2
Toast 组件:
<template>
<transition name="fade">
<div
v-show="show"
class="my-toast"
@touchmove.prevent>
<div class="mask" @click="onClose"></div>
<div class="content">
{{ content }}
</div>
</div>
</transition>
</template>
export default {
data () {
return {
show: false,
content: ''
}
},
methods: {
onClose () {
this.show = false
}
}
}
Toast.js
import Vue from 'vue'
import Toast from './myToast'
const toastConstructor = Vue.extend(Toast)
// 定义弹出组件的函数 接收2个参数, 要显示的文本 和 显示时间
function myToast (text, duration = 5000) {
// 实例化一个 toast.vue
const toast = new toastConstructor()
// 将组件对象手动挂载到某一个元素上
toast.$mount(document.createElement('div'))
// toast.$el对应的就是DIV
document.body.appendChild(toast.$el)
toast.content = text
toast.show = true
setTimeout(() => {
toast.show = false
}, duration)
}
export default myToast
使用:
<template>
<div>
<button @click="configClcik"></button>
<div>
</template>
<script>
import myToast from 'components/myToast'
methods: {
configClcik() {
myToast('弹出信息')
}
}
</script>
vue3
Toast 组件
<template>
<transition name="toast">
<div v-show="show" class="toast">{{ message }}</div>
</transition>
</template>
<script setup>
import {ref, unref} from "vue";
const show = ref(false)
const message = ref('')
const close = () => {
show.value = false
}
const open = (message, delay = 1000) => {
if (show.value) return
message.value = message
show.value = true
setTimeout(close, unref(delay))
}
defineExpose({open, close})
</script>
Toast.js
import {render, createVNode, VNode} from 'vue'
import Toast from './Toast.vue'
const createToast = () => {
const _vm = createVNode(Toast)
const container = document.createElement('div')
render(_vm, container)
document.body.appendChild(container)
return _vm
}
let toast = null
export const useToast = () => {
if (!toast) toast = createToast()
const toast = (message: string) => {
toast?.component?.exposed?.open(message)
}
return toast
}
使用
<template>
<button @click="toast('hello world')">button</button>
</template>
<script setup>
import useToast from "@/components/Toast";
const toast = useToast()
</script>