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

先来看一段代码

components/toast/index.vue

<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

<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文件,写入以下代码:

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

没有任何区别

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
UniApp是一个基于Vue.js的跨平台开发框架,可以同时开发iOS、Android、H5等多个平台的应用。Vue 3是Vue.js的最新版本,带来了许多新特性和改进。在UniApp中使用Vue 3和TypeScript来封装请求可以按照以下步骤进行: 1. 安装依赖:在UniApp项目中,首先需要安装axios库和@types/axios库,用于发送HTTP请求和提供TypeScript类型定义。 ```bash npm install axios @types/axios ``` 2. 创建请求封装文件:在项目的`src`目录下创建一个`api`文件夹,并在该文件夹下创建一个`request.ts`文件,用于封装请求相关的代码。 ```typescript import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'; // 创建axios实例 const instance = axios.create({ baseURL: 'http://api.example.com', // 设置请求的基础URL timeout: 5000, // 设置请求超时时间 }); // 请求拦截器 instance.interceptors.request.use( (config: AxiosRequestConfig) => { // 在发送请求之前做一些处理,例如添加token等 return config; }, (error) => { // 处理请求错误 return Promise.reject(error); } ); // 响应拦截器 instance.interceptors.response.use( (response: AxiosResponse) => { // 对响应数据进行处理,例如统一处理错误码等 return response.data; }, (error) => { // 处理响应错误 return Promise.reject(error); } ); // 封装GET请求 export function get(url: string, params?: any): Promise<any> { return instance.get(url, { params }); } // 封装POST请求 export function post(url: string, data?: any): Promise<any> { return instance.post(url, data); } // 其他请求方法的封装,例如PUT、DELETE等 ``` 3. 使用请求封装:在需要发送请求的地方,引入`request.ts`文件,并调用相应的请求方法。 ```typescript import { get, post } from '@/api/request'; // 发送GET请求 get('/user/info', { id: 1 }) .then((response) => { console.log(response); }) .catch((error) => { console.error(error); }); // 发送POST请求 post('/user/login', { username: 'admin', password: '123456' }) .then((response) => { console.log(response); }) .catch((error) => { console.error(error); }); // 其他请求方法的使用,例如PUT、DELETE等 ``` 以上就是在UniApp中使用Vue 3和TypeScript封装请求的基本步骤。你可以根据实际需求进行进一步的封装和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值