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')
})
相关推荐
社恐的下水道蟑螂2 小时前
LangChain 进阶实战:从玩具 Demo 到生产级 AI 应用(JS/TS 全栈版)
前端·langchain·openai
Fairy要carry2 小时前
项目01-手搓Agent之loop
前端·javascript·python
亲亲小宝宝鸭2 小时前
Ctrl ACV工程师的提效之路:删掉项目中的冗余
前端
kyriewen2 小时前
DOM树与节点操作:用JS给网页“动手术”
前端·javascript·面试
米饭同学i2 小时前
基于腾讯云COS的小程序素材上传功能实现
前端·javascript·react.js
cxxcode2 小时前
前端性能指标接入 Prometheus 技术方案
前端
辣椒炒代码2 小时前
🚀 AI Agent 入门实战:基于 LangChain + MCP 构建智能导游助手
前端
ruanCat2 小时前
前端工程化工具链从零配置:simple-git-hooks + lint-staged + commitlint
前端·git·代码规范
光影少年2 小时前
如何开发一个CLI工具?
javascript·测试工具·前端框架·node.js
哈__2 小时前
ReactNative项目OpenHarmony三方库集成实战:react-native-fingerprint-scanner
javascript·react native·react.js