uni-app/vue项目如何封装全局消息提示组件

效果图:

第一步:封装组件和方法,采用插件式注册!

在项目目录下新建components文件夹,里面放两个文件,分别是index.vue和index.js.

index.vue:

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

<script>
export default {
  name: 'AllToast',
  props: {
    isShow: {
      type: Boolean,
      required: true,
      default: false
    },
    message: {
      type: String,
      required: true,
      default: ''
    }
  },
  data() {
    return {};
  }
}
</script>

<style scoped>
.toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 9999;
  width: 300rpx;
  height: 100rpx;
  background-color: red;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  border-radius: 10rpx;
}
</style>

index.js:

复制代码
import Vue from 'vue'
import AllToast from './index.vue'

const ToastConstructor = Vue.extend(AllToast)

function showToast(message) {
  const instance = new ToastConstructor({
    el: document.createElement('view'),
    propsData: {
      isShow: true,
      message: message
    }
  })
  document.body.appendChild(instance.$el)

  setTimeout(() => {
    instance.isShow = false
    document.body.removeChild(instance.$el)
  }, 3000) // 3秒后自动隐藏
}

export default {
  install: function (vue) {
    vue.component('toast', AllToast)
    vue.prototype.$showToast = showToast
  }
}

第二步:全局挂载

在main.js中引入和使用

复制代码
import App from './App'
import uView from '@/uni_modules/uview-ui'
// 引入全局组件
import Mycomponent from '@/components/index.js'

// #ifndef VUE3
import Vue from 'vue'
Vue.use(uView)
// 挂载组件
Vue.use(Mycomponent)
import './uni.promisify.adaptor'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
  ...App
})
app.$mount()
// 测试使用
Vue.prototype.$showToast('请求失败');
// #endif

// #ifdef VUE3
import { createSSRApp } from 'vue'
export function createApp() {
  const app = createSSRApp(App)
  return {
    app
  }
}
// #endif

第三步:使用方法

vue页面使用

复制代码
this.$showToast('我是全局组件菜鸡')

其他页面使用

复制代码
//对于this指向不是vue的需要先引入vue
import Vue from 'vue'

//然后调用原型方法
Vue.prototype.$showToast('请求失败');

同理 这个方法也适用于Vue项目不止是uni

相关推荐
2501_9151063212 小时前
如何在 Mac 上面代理抓包和数据流分析
android·macos·ios·小程序·uni-app·iphone·webview
2501_9159214312 小时前
在 Linux 上通过命令行上架 iOS APP,Fastlane + AppUploader(开心上架)
android·linux·运维·ios·小程序·uni-app·iphone
2501_9159214313 小时前
从构建到 IPA 保护,Flutter iOS 包如何做混淆与安全处理
android·安全·flutter·ios·小程序·uni-app·iphone
2501_9160088913 小时前
iPhone 手机硬件组件使用耗能历史记录查看,能耗查看
android·ios·智能手机·小程序·uni-app·iphone·webview
游九尘13 小时前
uniapp查看下载文档,支持格式:doc, xls, ppt, pdf, docx, xlsx, pptx
uni-app
前端Hardy1 天前
用 uni-app x 重构我们的 App:一套代码跑通 iOS、Android、鸿蒙!人力成本直降 60%
前端·ios·uni-app
嘉琪0012 天前
uni-app 核心坑点及解决方案——2026 0309
uni-app
行者-全栈开发2 天前
uni-app 审批流程组件封装:打造企业级工作流可视化方案
uni-app
2501_916008892 天前
iPhone 上怎么抓 App 的网络请求,在 iOS 设备上捕获网络请求
android·网络·ios·小程序·uni-app·iphone·webview
jingling5552 天前
无需重新安装APK | uni-app 热更新技术实战
前端·javascript·前端框架·uni-app·node.js