vue3小程序 中封装组件 但是想在页面中直接获取使用的话可以 通过这样的方式

我们经常会封装许多模那种 loading  或者toast 这种内容,如果在页面上大量写的话  也会感觉代码很乱 所以我们可以简单封装一个 vue2 版本 或者 vue3 版本

1. 创建一个 toast.js 文件

export default function shortToast(title, icon = 'none') {
  if (typeof title !== 'string') {
    return;
  }
  uni.showToast({
    title,
    icon,
    duration: 2000,
    success: function() {
      console.log('Toast displayed successfully');
    },
    fail: function(err) {
      console.error('Failed to display toast:', err);
    }
  });
}

在vue2中 我们将这个文件导入main.js 文件 中

import {
  shortToast
} from '@/libs/Toast.js'

Vue.prototype.$toast = shortToast

在页面中我们可以直接 this. shortToast('内容')

在vue3 中

import App from './App'
import shortToast from './utils/toast'
// #ifndef VUE3
import Vue from 'vue'
import './uni.promisify.adaptor'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
  ...App
})
app.$mount()
// #endif

// #ifdef VUE3
import {
  createSSRApp
} from 'vue'
import store from './store/index.js'
export function createApp() {
  const app = createSSRApp(App)
  app.use(store)
  app.config.globalProperties.$toast = shortToast
  return {
    app
  }
}
// #endif

在页面中 引用的时候 我们就是通过这样的方法

<script setup>
  import {
    ref,
    reactive,
    getCurrentInstance
  } from 'vue'
  import {
    onLoad
  } from '@dcloudio/uni-app'
 
  const { proxy: { $toast} } = getCurrentInstance();

onLoad(()=>{
$toast('1111')
})

相关推荐

  1. 【无标题】Vue3scss使用动态变量

    2024-07-20 00:42:06       42 阅读
  2. vue3通过数据字典实现下拉选择框组件封装

    2024-07-20 00:42:06       25 阅读
  3. Vue3,父组件调用子组件方法

    2024-07-20 00:42:06       43 阅读
  4. vue不同组件通信方式

    2024-07-20 00:42:06       46 阅读
  5. Uniapp 和Vue3 程序 获取页面dom 方法

    2024-07-20 00:42:06       38 阅读
  6. 如何程序实现页面之间返回

    2024-07-20 00:42:06       23 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-20 00:42:06       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-20 00:42:06       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-20 00:42:06       45 阅读
  4. Python语言-面向对象

    2024-07-20 00:42:06       55 阅读

热门阅读

  1. 基于深度学习的车距检测系统

    2024-07-20 00:42:06       17 阅读
  2. 有些面试,纯属是浪费时间和精力!

    2024-07-20 00:42:06       14 阅读
  3. 手写简易版Spring IOC容器02【学习】

    2024-07-20 00:42:06       13 阅读
  4. 新手教程---python-函数(新添加)

    2024-07-20 00:42:06       19 阅读