Vue中自定义全局Toast

Vue中自定义全局Toast

徐徐
前端
发布于2024-08-24 17:23:37
🌺前言
vue中自定义Toast轻提示

1.定义Toast组件

vue
<template>
  <Transition name="up">
    <div
      v-show="visible"
      class="toasts">
      <iconfont
        :icon-class="iconClass"
        style="width: 20px;height: 20px;"/>
      <span>{{ text }}</span>
    </div>
  </Transition>
</template>
<script lang="ts" setup>
import { ref, toRefs } from 'vue'
const props = defineProps({
  text: {
    type: String,
    default: ''
  },
  type: {
    type: String,
    default: 'info'
  }
})
const { text } = toRefs(props)
const iconClass = computed(() => {
  if (props.type === 'success') return 'icon-chenggong'
  if (props.type === 'error') return 'icon-71shibai'
  if (props.type === 'warning') return 'icon-jinggao'
  if (props.type === 'info') return 'icon-chanpinxinxi'
  return 'icon-chanpinxinxi'
})
const visible = ref<boolean>(false)

visible.value = true
</script>
<style scoped lang="scss">
.toasts {
  padding: 0 15px;
  // min-width: 200px;
  height: 42px;
  position: fixed;
  z-index: 99999;
  left: 50%;
  top: 16%;
  background-color: #fff;
  box-shadow:0 3px 6px -4px #0000001f,0 6px 16px #00000014,0 9px 28px 8px #0000000d;
  color: #000000d9;
  border-radius: 5px;
  display: flex;
  align-items: center;
  gap: 3px;
  font-size: 14px;
  transform: translateX(-50%) translateY(-50%);
  line-height: 48px;
  white-space: pre;
}
.up-enter-from {
  opacity: 0;
}
.up-enter-active {
  transition: all 0.5s;
}
.up-enter-to {
  opacity: 1;
}
</style>

2.定义函数的方式调用

typescript
import { createVNode, render } from "vue";
import Toast from "@/components/Toast.vue";
// let time: number | null = null;
let time: string | number | NodeJS.Timeout | undefined
interface ToastType{
  text:string
  type?:'success'|'error'|'info'|'warning'
  duration?:number
}
export const toast = (params:ToastType|string): void => {
  let text = ''
  let type = 'info'
  let duration = 3000
  if (typeof params === 'string'){
    text = params
  } else {
    text = params.text||''
    type = params.type||'info'
    duration = params.duration||3000
  }
  const div = document.createElement("div");
  div.setAttribute("class", "toast-box");
  document.body.appendChild(div);
  const NODE = createVNode(Toast, { text,type });
  render(NODE, div);
  time && clearTimeout(time);
  time = setTimeout(() => {
    render(null, div);
    const toastList = document.body.querySelectorAll(".toast-box");
    for (let i = 0; i < toastList.length; i++) {
      document.body.removeChild(toastList[i]);
    }
  }, duration);
};

3.在组件内调用该函数

(略)

目录

文章最后更新于 2024-08-30 16:28:54
留言
暂无数据

~~空空如也