封装一个vue3 Toast组件,支持组件和api调用

先来看一段代码

components/toast/index.vue

html 复制代码
<template>
  <div v-if="isShow" class="toast">
    {{msg}}
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  msg: {
    type: String,
    default: 'message',
  },
  duration: {
    type: Number,
    default: 1500
  }
})

const isShow = ref(props.show)
const emit = defineEmits(['update:show'])

watch(() => props.show, (newVal, oldVal) => {
  isShow.value = newVal
  if (newVal) {
    clearInterval(timer)
    var timer = setTimeout(() => {
      isShow.value = false
      emit('update:show', false)
    }, props.duration)
  }
})
</script>

<style scoped>
  .toast {
    position: fixed;
    top: 200px;
    left: 50%;
    transform: translateX(-50%);
    padding: 4px 8px;
    background-color: rgba(0, 0, 0, .8);
    border-radius: 4px;
    color: #fff;
  }
</style>

这就是一个普通的Toast组件

  • show:是否显示
  • msg:弹窗内容
  • duration:多少毫秒后自动关闭

调用组件

views/toast.view

html 复制代码
<template>
  <Toast v-model:show="isShow" msg="hello toast" :duration="2000"></Toast>
  <button @click="isShow = true">组件调用</button>
</template>

<script setup>
  import { ref } from 'vue'
  import Toast from '@/components/toast/index.vue'
  const isShow = ref(false)
</script>

我们平时都是这么用的

但是这个组件只能在.vue组件中使用,现在我的项目中正在封装一个全局axios拦截器request.js,就没办法这么用了。

封装api

components/toast目录下,与index.vue同级,再新建一个index.js文件,写入以下代码:

js 复制代码
import { createApp } from 'vue'
import Toast from './index.vue'

const showToast = (msg, options = { duration: 1500 }) => {
  const { duration } = options
  const div = document.createElement('div')
  const componentInstance = createApp(Toast, {
    show: true,
    msg,
    duration
  })

  componentInstance.mount(div)
  document.body.appendChild(div)
  
  let timer = null
  clearTimeout(timer)
  timer = setTimeout(() => {
    componentInstance.unmount(div); 
    document.body.removeChild(div);
  }, duration)
}

export default showToast

然后就可以在任意地方调用showToast方法。

在main.js调用

再来看看为什么components/toast/index.js能做到这个效果

  1. vue中解构出createApp,看到这个是不是很熟悉?对,就是main.js中我们看到的那个createApp

  2. 引入写好的toast组件,传给createApp,得到一个组件实例

  3. 将组件实例挂载到一个动态创建的div元素上

  4. 将div元素追加到body元素中

再看看main.js

没有任何区别

相关推荐
程序员是干活的1 天前
私家车开车回家过节会发生什么事情
java·开发语言·软件构建·1024程序员节
freellf9 天前
数据结构及基本算法
1024程序员节
BruceGerGer1 个月前
flutter开发实战-flutter web加载html及HtmlElementView的使用
flutter·1024程序员节
网络冒险家2 个月前
【软考】系统集成项目管理工程师【第二版】
职场和发展·软考·集成学习·1024程序员节·系统集成项目工程师
BruceGerGer2 个月前
flutter开发实战-AssetBundle读取指定packagename的文件
flutter·1024程序员节
sheng12345678rui2 个月前
最新缺失msvcp140.dll的多种解决方法,有效解决电脑dll问题
windows·microsoft·电脑·dll文件·1024程序员节
a5553338203 个月前
电脑显示mfc140u.dll丢失的修复方法,总结7种有效的方法
java·经验分享·dll·dll文件丢失·1024程序员节
行十万里人生3 个月前
C++ 智能指针
linux·c++·git·阿里云·容器·蓝桥杯·1024程序员节
a5553338203 个月前
启动鸣潮提示错误代码126:加载d3dcompiler_43.dll错误或缺失的7个解决方法
前端·经验分享·dll·dll文件丢失·1024程序员节
BruceGerGer3 个月前
flutter开发实战-Webview及dispose关闭背景音
flutter·1024程序员节