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

相关推荐
林涧泣20 小时前
【Uniapp-Vue3】解决uni-popup弹窗在安全区显示透明问题
前端·vue.js·uni-app
寰宇软件3 天前
PHP场馆预定系统小程序
小程序·uni-app·vue·php
林涧泣3 天前
【Uniapp-Vue3】触底加载更多
uni-app
新青年.3 天前
【uniapp】uniapp使用java线程池
javascript·uni-app
答题卡上的情书3 天前
uniapp版本升级
前端·javascript·uni-app
向明天乄3 天前
uniapp 地图添加,删除,编辑标记,在地图中根据屏幕范围中呈现标记
android·java·uni-app
大叔_爱编程3 天前
wx044基于springboot+vue+uniapp的智慧物业平台小程序
vue.js·spring boot·小程序·uni-app·毕业设计·源码·课程设计
林涧泣4 天前
【Uniapp-Vue3】图片lazy-load懒加载
uni-app
大叔_爱编程5 天前
wx043基于springboot+vue+uniapp的智慧物流小程序
vue.js·spring boot·小程序·uni-app·毕业设计·源码·课程设计
林涧泣6 天前
【Uniapp-Vue3】StorageSync数据缓存API
前端·javascript·uni-app