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

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

  1. 创建一个 toast.js 文件
javascript 复制代码
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 文件 中

javascript 复制代码
import {
  shortToast
} from '@/libs/Toast.js'

Vue.prototype.$toast = shortToast

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

在vue3 中

javascript 复制代码
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

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

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

onLoad(()=>{
$toast('1111')
})
相关推荐
IT_陈寒7 分钟前
Vite静态资源加载把我坑惨了
前端·人工智能·后端
herinspace8 分钟前
管家婆实用贴-如何分离和附加数据库
开发语言·前端·javascript·数据库·语音识别
小码哥_常33 分钟前
从MVC到MVI:一文吃透架构模式进化史
前端
嗷o嗷o33 分钟前
Android BLE 的 notify 和 indicate 到底有什么区别
前端
豹哥学前端37 分钟前
别再背“var 提升,let/const 不提升”了:揭开暂时性死区的真实面目
前端·面试
Lkstar41 分钟前
我把Vue2响应式源码从头到尾啃了一遍,这是整理笔记
vue.js
lar_slw1 小时前
k8s部署前端项目
前端·容器·kubernetes
这里不能睡觉1 小时前
js 实现 Blob、File、ArrayBuffer、base64、URL 之间互转
javascript
拉拉肥_King1 小时前
Ant Design Table 横向滚动条神秘消失?我是如何一步步找到真凶的
前端·javascript
GreenTea1 小时前
DeepSeek-V4 技术报告深度分析:基础研究创新全景
前端·人工智能·后端