当前位置:   article > 正文

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

uniapp 封装全局totast

效果图:

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

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

index.vue:

  1. <template>
  2. <div class="toast" v-if="isShow">
  3. {{ message }}
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. name: 'AllToast',
  9. props: {
  10. isShow: {
  11. type: Boolean,
  12. required: true,
  13. default: false
  14. },
  15. message: {
  16. type: String,
  17. required: true,
  18. default: ''
  19. }
  20. },
  21. data() {
  22. return {};
  23. }
  24. }
  25. </script>
  26. <style scoped>
  27. .toast {
  28. position: fixed;
  29. top: 50%;
  30. left: 50%;
  31. transform: translate(-50%, -50%);
  32. z-index: 9999;
  33. width: 300rpx;
  34. height: 100rpx;
  35. background-color: red;
  36. display: flex;
  37. justify-content: center;
  38. align-items: center;
  39. color: #fff;
  40. border-radius: 10rpx;
  41. }
  42. </style>

index.js:

  1. import Vue from 'vue'
  2. import AllToast from './index.vue'
  3. const ToastConstructor = Vue.extend(AllToast)
  4. function showToast(message) {
  5. const instance = new ToastConstructor({
  6. el: document.createElement('view'),
  7. propsData: {
  8. isShow: true,
  9. message: message
  10. }
  11. })
  12. document.body.appendChild(instance.$el)
  13. setTimeout(() => {
  14. instance.isShow = false
  15. document.body.removeChild(instance.$el)
  16. }, 3000) // 3秒后自动隐藏
  17. }
  18. export default {
  19. install: function (vue) {
  20. vue.component('toast', AllToast)
  21. vue.prototype.$showToast = showToast
  22. }
  23. }

第二步:全局挂载

在main.js中引入和使用

  1. import App from './App'
  2. import uView from '@/uni_modules/uview-ui'
  3. // 引入全局组件
  4. import Mycomponent from '@/components/index.js'
  5. // #ifndef VUE3
  6. import Vue from 'vue'
  7. Vue.use(uView)
  8. // 挂载组件
  9. Vue.use(Mycomponent)
  10. import './uni.promisify.adaptor'
  11. Vue.config.productionTip = false
  12. App.mpType = 'app'
  13. const app = new Vue({
  14. ...App
  15. })
  16. app.$mount()
  17. // 测试使用
  18. Vue.prototype.$showToast('请求失败');
  19. // #endif
  20. // #ifdef VUE3
  21. import { createSSRApp } from 'vue'
  22. export function createApp() {
  23. const app = createSSRApp(App)
  24. return {
  25. app
  26. }
  27. }
  28. // #endif

第三步:使用方法

vue页面使用

this.$showToast('我是全局组件菜鸡')

其他页面使用

  1. //对于this指向不是vue的需要先引入vue
  2. import Vue from 'vue'
  3. //然后调用原型方法
  4. Vue.prototype.$showToast('请求失败');

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/985614
推荐阅读
相关标签
  

闽ICP备14008679号