Technology sharing

Quomodo uni-app/vue proiectum encapsulat nuntius globalis prompti componentis?

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Reddendo:

Gradus unus: Encapsulate componentes et modos et utere obturaculum-in adnotatione!

Novam partem folder in indice project et duos fasciculos in eo pone, scilicet index.vue et 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. }

Gradus II: Mount globally

Introducti et usus in 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

Gradus III, quomodo uti

vue pagina usus

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

Utere in aliis paginis

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

Eodem modo haec ratio quoque valetVue projectPlus quam uni-