uni-app main.js中全局变量的使用方法示例
作者:Bingo_BIG
在进行uni-app开发时,全局变量的合理使用对于提升开发效率和项目管理具有重要意义,这篇文章主要给大家介绍了关于uni-app main.js中全局变量的使用方法,需要的朋友可以参考下
main.js
import App from './App'; import store from './store'; import request from '@/http/request.js'; // #ifndef VUE3 import Vue from 'vue'; Vue.config.productionTip = false; Vue.prototype.$store = store; Vue.prototype.$adpid = '1111111111'; Vue.prototype.$backgroundAudioData = { playing: false, playTime: 0, formatedPlayTime: '00:00:00' }; Vue.prototype.$request = request; // 设置全局变量和函数(Vue 2) Vue.prototype.$globalData = null; Vue.prototype.$setGlobalData = (data) => { Vue.prototype.$globalData = data; }; Vue.prototype.$getGlobalData = () => { return Vue.prototype.$globalData; }; Vue.prototype.$globalData2 = null; Vue.prototype.$setGlobalData2 = (data) => { Vue.prototype.$globalData2 = data; }; Vue.prototype.$getGlobalData2 = () => { return Vue.prototype.$globalData2; }; Vue.prototype.$globalData3 = null; Vue.prototype.$setGlobalData3 = (data) => { Vue.prototype.$globalData3 = data; }; Vue.prototype.$getGlobalData3 = () => { return Vue.prototype.$globalData3; }; //////////////// App.mpType = 'app'; const app = new Vue({ store, ...App }); app.$mount(); // #endif // #ifdef VUE3 import { createSSRApp } from 'vue'; export function createApp() { const app = createSSRApp(App); app.use(store); app.config.globalProperties.$adpid = '1111111111'; app.config.globalProperties.$backgroundAudioData = { playing: false, playTime: 0, formatedPlayTime: '00:00:00' }; app.config.globalProperties.$request = request; // 注意:在 Vue 3 中,全局变量和函数应该直接设置在 app.config.globalProperties 上, // 而不是像 Vue 2 那样通过 Vue.prototype。但是,为了保持一致性,并且能够在组件中 // 通过 this.$xxx 的方式访问,我们仍然可以在这里设置它们。 // 不过,通常建议通过组合式 API 的 getCurrentInstance 来访问这些全局属性。 app.config.globalProperties.$globalData = null; app.config.globalProperties.$setGlobalData = (data) => { app.config.globalProperties.$globalData = data; }; app.config.globalProperties.$getGlobalData = () => { return app.config.globalProperties.$globalData; }; app.config.globalProperties.$globalData2 = null; app.config.globalProperties.$setGlobalData2 = (data) => { app.config.globalProperties.$globalData2 = data; }; app.config.globalProperties.$getGlobalData2 = () => { return app.config.globalProperties.$globalData2; }; app.config.globalProperties.$globalData3 = null; app.config.globalProperties.$setGlobalData3 = (data) => { app.config.globalProperties.$globalData3 = data; }; app.config.globalProperties.$getGlobalData3 = () => { return app.config.globalProperties.$globalData3; }; //////////////// return { app }; } // #endif
调用
import { reactive, ref, getCurrentInstance } from 'vue'; const instance = getCurrentInstance(); //给全局变量赋值 let item={}; instance.appContext.config.globalProperties.$setGlobalData(item); //取全局变量参数 const globalData = instance.appContext.config.globalProperties.$getGlobalData();
vue页面--调用页面
<template> <z-paging ref="paging" v-model="dataList" @query="queryList"> <template #top> <view class="searchForm"> <view> <uni-easyinput v-model="tj0MachineNumbe" name="tj0MachineNumbe" placeholder="输入机台号" prefixIcon="scan" @confirm="onInput"> </uni-easyinput> </view> <view class="select-itme"> <view> <button type="primary" @click="printLabels" plain="true">打印容器标签</button> </view> <view> <button type="primary" @click="startPickingMaterials">开始拣料</button> </view> </view> </view> <view style="margin: 0 10rpx; "> <uni-segmented-control :current="current" :values="items" @clickItem="onClickItem" styleType="button" :active-color="activeColor"> </uni-segmented-control> </view> </template> <view class="content"> <view class="container"> <!-- 渲染列表 --> <view v-for="(item, index) in dataList" :key="item.objId" class="student-item" @tap="toggleSelection(item.objId)"> <view class="example-body"> <uni-row class="demo-uni-row"> <uni-col :span="14"> <!-- 序号 --> <view class="field">拣料单: {{ item.orderNumber }}</view> </uni-col> <uni-col :span="10"> <!-- 机台 --> <view class="field">机台: {{ item.tj0MachineNumbe }}</view> </uni-col> <uni-col :span="14"> <!-- 工单号 --> <view class="field">工单号: {{ item.tj0OrderCode}}</view> </uni-col> <uni-col :span="10"> <!-- 类型 --> <view class="field">类型: {{ item.tj0type }}</view> </uni-col> </uni-row> </view> <view class="item-arrow"> <!-- 复选框 --> <checkbox :value="item.objId" @tap="toggleSelection(item.objId)" :checked="isSelected(item.objId)" class="checkbox"></checkbox> </view> </view> <!-- 显示已选择的项数 --> <view class="selected-count" style="display: none;">已选择:{{ selectedIds.length }} 项</view> <!-- 全选/取消全选按钮 --> <!--<button @click="toggleSelectAll">{{ isAllSelected ? '取消全选' : '全选' }}</button>--> </view> </view> </z-paging> </template> <script setup> import { ref, reactive, computed, getCurrentInstance } from 'vue'; import { queryPage, seachJobTaskList } from "@/api/pickingTask"; const instance = getCurrentInstance(); const paging = ref(null); const dataList = ref([]); const activeColor = ref("#0049dd"); const items = ['待拣料', '拣料中', '拣料完成']; const current = ref(0); const tj0MachineNumbe = ref(""); //查询 const onInput = (e) => { paging.value.reload(); }; const onClickItem = (e) => { current.value = e.currentIndex; // 获取当前选中的索引 paging.value.reload(); }; // @query所绑定的方法不要自己调用!!需要刷新列表数据时,只需要调用paging.value.reload()即可 const queryList = (pageNo, pageSize) => { // 组件加载时会自动触发此方法,因此默认页面加载时会自动触发,无需手动调用 // 这里的pageNo和pageSize会自动计算好,直接传给服务器即可 // 模拟请求服务器获取分页数据,请替换成自己的网络请求 const params = { "attrSet": [], "condition": [], "sorts": [{ "name": "createAt", "sort": "desc" }], "page": { "pageNo": pageNo, "pageSize": pageSize } }; if (tj0MachineNumbe.value != '') { params.condition.push({ "compare": "LIKE", "field": "tj0MachineNumbe", "value": tj0MachineNumbe.value }); } if (current.value == 0) { //收货中 params.condition.push({ "compare": "EQUAL", "field": "orderStatus", "value": 'Created' //“已创建” }); } else if (current.value == 1) { //待收货 params.condition.push({ "compare": "EQUAL", "field": "orderStatus", "value": 'CKZ' //出库中” }); } if (current.value == 2) { //已收货 params.condition.push({ "compare": "EQUAL", "field": "orderStatus", "value": 'CKWC' //CKWC “出库完成” }); } queryPage(params).then(res => { console.log("============", JSON.stringify(res)); if (res.code == 0) { // 将请求的结果数组传递给z-paging paging.value.complete(res.data); } else { //异常信息 paging.value.complete(false); uni.showToast({ title: res.msg }); } }).catch(res => { // 如果请求失败写paging.value.complete(false); // 注意,每次都需要在catch中写这句话很麻烦,z-paging提供了方案可以全局统一处理 // 在底层的网络请求抛出异常时,写uni.$emit('z-paging-error-emit');即可 paging.value.complete(false); }); }; // 记录选中的id const selectedIds = ref([]); // 计算是否已全选 const isAllSelected = computed(() => { return selectedIds.value.length === dataList.length; }); // 判断是否被选中 const isSelected = (id) => { return selectedIds.value.includes(id); }; // 切换选中状态 const toggleSelection = (id) => { const index = selectedIds.value.indexOf(id); if (index === -1) { selectedIds.value.push(id); // 如果没选中,加入选中 } else { selectedIds.value.splice(index, 1); // 如果已选中,取消选中 } }; // 切换全选状态 const toggleSelectAll = () => { if (isAllSelected.value) { selectedIds.value = []; // 取消全选 } else { selectedIds.value = dataList.map(item => item.objId); // 全选 } }; //打印容器标签 const printLabels = (e) => { }; //开始拣料 const startPickingMaterials = (e) => { //console.log(JSON.stringify(selectedIds.value)) //勾选的数据ID if (selectedIds.value.length == 0) { uni.showToast({ title: '至少选择一条数据', icon: 'none', // 无图标,只显示文本 duration: 2000, // 显示2秒 mask: true, // 显示遮罩层,避免点击背景关闭 }); return; } instance.appContext.config.globalProperties.$setGlobalData(selectedIds.value); uni.navigateTo({ url: '/pages/pickingTask/pickingExecution' }); // let listObjId = JSON.stringify(selectedIds.value); // //console.log(encodeURIComponent(listObjId)) ; // uni.navigateTo({ // url: '/pages/pickingTask/pickingExecution?data=' + encodeURIComponent(listObjId) // }) }; </script> <style scoped lang="scss"> view { box-sizing: border-box; color: $uni-text-color; } button { font-size: $uni-btn-font-size !important; } .searchForm { background-color: white; padding: 20rpx 10rpx; } .select-itme { display: flex; margin-top: 10rpx; } .select-itme>view:nth-child(1) { margin-right: 5rpx; } .select-itme>view { flex: 1; } .col-item { margin: 5px; } .container { padding: 5px; } .student-item { margin-bottom: 8rpx; border: 1px solid #ddd; padding: 10px; border-radius: 6px; display: flex; align-items: center; background-color: white; } .student-item view:nth-child(1) { flex: 90%; } .student-item view:nth-child(1) { flex: 10%; } .field { margin: 5px 0; font-size: 14px; } .checkbox { margin-left: 10px; } .selected-count { margin-top: 20px; color: #007aff; } </style>
vue页面-取值页面
<template> <z-paging ref="paging" v-model="dataList" @query="queryList"> <view class="container" v-for="(row, index) in dataList" :key="index" @click="cardClick(row)"> <!-- 表格 --> <view class="table"> <!-- 遍历每一行数据 --> <view class="table-row"> <!-- 每行的物料号和总需求数量 --> <view class="row-header"> <view class="material-info"> <text class="label blueBar">物料号:</text> <text class="value">{{ row.matrialCode }}</text> </view> <view class="material-info"> <text class="label">总需求数量:</text> <text class="value">{{ row.totalqty }}</text> </view> </view> <!-- 嵌套的表格 --> <view class="nested-table"> <view class="nested-table-header"> <view class="table-cell2">类型</view> <view class="table-cell2">数量</view> <view class="table-cell">推荐库位</view> <view class="table-cell">工单</view> </view> <view class="nested-table-body"> <view class="nested-table-row" v-for="(item, index) in row.taskline" :key="index"> <view class="table-cell2">{{ item.materialType }}</view> <view class="table-cell2">{{ item.operateQuantity }}</view> <view class="table-cell">{{ item.tj0RecommendStorageLocation }}</view> <view class="table-cell">{{ item.tj0OrderCode }}</view> </view> </view> </view> </view> </view> <view class="item-arrow"> <uni-icons type="right" size="25" color="gray"></uni-icons> </view> </view> </z-paging> <view> <!-- 提示信息弹窗 --> <uni-popup ref="refMessage" type="message"> <uni-popup-message :type="msgType" :message="messageText" :duration="2000"></uni-popup-message> </uni-popup> </view> </template> <script setup> import { nextTick, onMounted, reactive, ref, getCurrentInstance } from "vue"; import { seachJobTaskList } from "@/api/pickingTask"; const instance = getCurrentInstance(); const paging = ref(); const dataList = ref([]); //提示消息 const refMessage = ref(); const msgType = ref(); const messageText = ref(); var objIds = []; const messageToggle = (type, msg) => { messageText.value = msg; msgType.value = type; refMessage.value.open('top'); }; // @query所绑定的方法不要自己调用!!需要刷新列表数据时,只需要调用paging.value.reload()即可 const queryList = (pageNo, pageSize) => { // 组件加载时会自动触发此方法,因此默认页面加载时会自动触发,无需手动调用 // 这里的pageNo和pageSize会自动计算好,直接传给服务器即可 // 模拟请求服务器获取分页数据,请替换成自己的网络请求 const params = objIds; console.log("objIds----------", JSON.stringify(objIds)); seachJobTaskList(params).then(res => { console.log("============", JSON.stringify(res)); if (res.code == 0) { // 将请求的结果数组传递给z-paging paging.value.complete(res.data); } else { //异常信息 paging.value.complete(false); uni.showToast({ title: res.msg }); } }).catch(res => { // 如果请求失败写paging.value.complete(false); // 注意,每次都需要在catch中写这句话很麻烦,z-paging提供了方案可以全局统一处理 // 在底层的网络请求抛出异常时,写uni.$emit('z-paging-error-emit');即可 paging.value.complete(false); }); }; const tableData = ref([]); const cardClick = (item) => { instance.appContext.config.globalProperties.$setGlobalData2(item); uni.navigateTo({ url: '/pages/pickingTask/taskExecution' }); // console.log("item ----------", JSON.stringify(item)); // let infoData = JSON.stringify(item) // let newStr = encodeURIComponent(infoData); // uni.navigateTo({ // url: '/pages/pickingTask/taskExecution?data=' + newStr // }); } onMounted(() => { //取全局变量参数 const globalData = instance.appContext.config.globalProperties.$getGlobalData(); let arrayId = globalData; objIds = arrayId.map((ite) => { return { "objId": ite }; }); /* const pages = getCurrentPages(); const currentPage = pages[pages.length - 1]; // 当前页面 //console.log("currentPage --------", currentPage); //父页面data参数 if (currentPage.options && currentPage.options.data) { let infoData = decodeURIComponent(currentPage.options.data); console.log("infoData----------", JSON.stringify(infoData)); let arrayId = JSON.parse(infoData); objIds = arrayId.map((ite) => { return { "objId": ite }; }); if (item.value.remark != null && item.value.remark != "") { BtnDisabled.value = true; } } */ console.log("onReady"); }); </script> <style scoped lang="scss"> view { box-sizing: border-box; //color: $uni-text-color; } .searchForm { background-color: $uni-bg-color; padding: 12rpx; } .container { padding: 12rpx 0 12rpx 12rpx; display: flex; align-items: center; justify-content: center; border: 1px solid $uni-border-color; border-radius: 6px; background-color: $uni-bg-color; margin-bottom: 5px; margin: 20rpx 10rpx; } .table { overflow: hidden; flex: 98%; } .item-arrow { flex: 2%; margin-left: 5px; } .table-row {} .row-header { display: flex; color: $uni-tab-activeColor; } .row-header>view:nth-child(1) { flex: 65%; } .row-header>view:nth-child(2) { flex: 35%; } .material-info { display: flex; margin-right: 20px; } .label { //font-weight: bold; margin-right: 5px; } .value { color: $uni-tab-activeColor; } .nested-table { overflow-x: auto; overflow: hidden; } .nested-table-header { @extend .nested-table-row; font-weight: bold; margin-top: 6rpx; } .nested-table-body { flex-direction: column; } .nested-table-row { display: flex; padding: 8px 5px; border-bottom: 1px solid $uni-border-color; } .table-cell { flex: 1; text-align: center; /* 允许文本换行 */ white-space: normal; /* 或者使用 overflow-wrap: break-word; */ word-wrap: break-word; overflow-wrap: break-word; min-width: 200rpx; } .table-cell2 { flex: 1; text-align: center; max-width: 130rpx; } .nested-table-row:last-child .table-cell { border-bottom: none; } .table-cell:last-child { // border-right: none; } //蓝色条块 .blueBar { margin-left: 2rpx; } .blueBar::before { white-space: pre; content: " "; background-color: $uni-border-bar-color; // $uni-color-primary ; width: 4px; /* 竖块的宽度 */ height: 12px !important; border-radius: 10px; margin-right: 15rpx; } </style>
总结
到此这篇关于uni-app main.js中全局变量的使用的文章就介绍到这了,更多相关uni-app main.js全局变量使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!