封装一个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 没有任何区别

相关推荐
小笔学长17 分钟前
Webpack 配置优化:提高打包速度与质量
前端·项目实战·前端开发·webpack优化·打包性能优化
优爱蛋白25 分钟前
SCF His Tag 重组蛋白:c-Kit受体信号研究与干细胞培养应用的关键试剂
前端·人工智能·健康医疗
C_心欲无痕31 分钟前
react - Suspense异步加载组件
前端·react.js·前端框架
JosieBook38 分钟前
【Vue】05 Vue技术——Vue 数据绑定的两种方式:单向绑定、双向绑定
前端·javascript·vue.js
想学后端的前端工程师1 小时前
【浏览器工作原理与性能优化指南:深入理解Web性能】
前端·性能优化
程序员爱钓鱼1 小时前
Node.js 编程实战:错误处理与安全防护
前端·后端·node.js
Geoffwo1 小时前
Electron 打包后 exe 对应的 asar 解压 / 打包完整流程
前端·javascript·electron
柒@宝儿姐1 小时前
vue3中使用element-plus的el-scrollbar实现自动滚动(横向/纵横滚动)
前端·javascript·vue.js
程序员爱钓鱼1 小时前
Node.js 编程实战:模板引擎与静态资源
前端·后端·node.js
Geoffwo1 小时前
Electron打包的软件如何使用浏览器插件
前端·javascript·electron