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')
})
相关推荐
东东51634 分钟前
基于ssm的网上房屋中介管理系统vue
前端·javascript·vue.js
harrain2 小时前
什么!vue3.4开始,v-model不能用在prop上
前端·javascript·vue.js
阿蒙Amon7 小时前
TypeScript学习-第7章:泛型(Generic)
javascript·学习·typescript
睡美人的小仙女1277 小时前
Threejs加载环境贴图报错Bad File Format: bad initial token
开发语言·javascript·redis
fanruitian7 小时前
uniapp android开发 测试板本与发行版本
前端·javascript·uni-app
rayufo7 小时前
【工具】列出指定文件夹下所有的目录和文件
开发语言·前端·python
RANCE_atttackkk7 小时前
[Java]实现使用邮箱找回密码的功能
java·开发语言·前端·spring boot·intellij-idea·idea
摘星编程8 小时前
React Native + OpenHarmony:Timeline垂直时间轴
javascript·react native·react.js
2501_944525549 小时前
Flutter for OpenHarmony 个人理财管理App实战 - 支出分析页面
android·开发语言·前端·javascript·flutter
jin1233229 小时前
React Native鸿蒙跨平台完成剧本杀组队详情页面,可以复用桌游、团建、赛事等各类组队详情页开发
javascript·react native·react.js·ecmascript·harmonyos