首页 > 其他分享 >uni-app 踩坑之旅2

uni-app 踩坑之旅2

时间:2023-04-13 16:55:25浏览次数:33  
标签:const name app export uni data response

首先是 axios ,拿到 uni-app 测试项目中,不好使,需要改成自带的 uni.request 请求,于是乎重新封装了下 request:
https://uniapp.dcloud.net.cn/api/request/request.html

import {
    getItem,
    removeItem,
    StorageKey
} from './storage';

function service(options) { // { url, method, data }

    options.header = {
        'content-type': 'application/json',
        'Authorization': 'Bearer ' + (getItem(StorageKey.token)?.token || ''),
    };

    return new Promise((resolved, rejected) => {
        options.success = (response) => {
            if (!response.data.status && response.data.code === 312) {
                // clearStorage(localTranslate('lang.message.' + error.response.code));
                clearStorage('');
            } else if (!response.data.status && response.data.code !== 200) {
                // 服务器请求错误
                // ElMessage.error(localTranslate('lang.message.' + response.data.code));                    
                rejected(res)
            } else if (response.data.status && response.data.code > 300) {
                // 后台程序错误
                // ElMessage.error(localTranslate('lang.message.' + response.data.code));
            }
            resolved(response.data)
        };
        options.fail = (err) => {
            // clearStorage(localTranslate('lang.message.' + error.response.code));
            clearStorage('');
            rejected(err);
        };
        uni.request(options);
    });
}

const clearStorage = mes => {
    // ElMessage.error(mes);
    setTimeout(() => {
        removeItem(StorageKey.token);
        removeItem(StorageKey.tag);
        removeItem(StorageKey.permission);

        uni.reLaunch({
            url: '/pages/login/login'
        });
    }, 500);
};


export default service;

 

接着,localStorage 也用不了,同样使用 底层缓存方式统一处理:

https://uniapp.dcloud.net.cn/api/storage/storage.html#setstorage

/*
 * localstorage 处理
 */
import { GetConfigPower } from "@/api/project";

export const getItem = name => {
    // 从本地缓存中同步获取指定 key 对应的内容。
    let data = null;
    try {
        data = uni.getStorageSync(name);
    } catch (err) {
        // error
    }

    try {
        return JSON.parse(data);
    } catch (err) {
        return data;
    }
};

export const setItem = (name, value) => {
    if (typeof value === 'object') {
        value = JSON.stringify(value);
    }
    // 将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个异步接口。
    uni.setStorage({
        key: name,
        data: value,
        success: () => {},
        fail: () => {},
    });
    
};

export const removeItem = name => {
    // 从本地缓存中异步移除指定 key。
    uni.removeStorage({
        key: name,
        success: () => {}
    });
};

// 获取标识信息
export const getSign = name => {
    return getItem(getUniqueKey(name));
};

// 存储标记信息
export const setSign = (name, value) => {
    setItem(getUniqueKey(name), value);
};

// 移除标识信息
export const removeSign = name => {
    removeItem(getUniqueKey(name));
};

// 登出时,清空关联性缓存
export const clearAllSign = n => {
    let id = getItem(StorageKey.token)?.id;
    const keys = Object.keys(localStorage);
    if (keys && keys.length) {
        keys.map(key => {
            if (key.match(id)) {
                removeItem(key);
            }
        });
    }
};

// 根据当前用户信息+数据标记,拼接唯一标识(用于区分 localStorage 数据)
export const getUniqueKey = name => {
    return getItem(StorageKey.token)?.id + `-${name}`;
};

/**
 * localStorage 键名
 */
export const StorageKey = {
    language: 'currentLanguage',
    token: 'token',
    partPageType: 'partPageType', // 列表页类型
    collapse: 'collapse', // 是否折叠
    tag: 'tag', // tag列表
    permission: 'permission', // 权限列表
    config: 'config', // 常用配置跳转
};

 

最后要提一下国际化,按照资料来即可,之前直接拿的pc 端项目,国际化的文件路径没对应上,导致翻译使始终出不来:

https://uniapp.dcloud.net.cn/tutorial/i18n.html#

pages.json 中的国际化,需要有对应 locale 的 翻译 json 文件!!!

标签:const,name,app,export,uni,data,response
From: https://www.cnblogs.com/guofan/p/17315422.html

相关文章

  • uniapp 使用cli模式,利用jenkins远程部署
    1、uniapp必须使用cli模式,如果是hbuliderx创建的,不支持2、jenkins配置需要publishoverssh插件和node插件,自行百度即可现在主要说说配置1)、系统管理-》系统配置中,找到publishoverssh 2          ......
  • Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not fi
    用idea使用mybatis时<mappers><mapperresource="com/mybatis/mapper/UserMapper.xml"></mapper></mappers>遇到吐下错误时ErrorparsingSQLMapperConfiguration.Cause:java.io.IOException:Couldnotfindresourcecom/my......
  • 微信小程序嵌套的webview页面实现导航,可跳转高德百度等app
    需求:微信小程序中使用webview嵌套了h5页面,h5页面中有经纬度,需要实现唤醒高德app。实现思路:此处h5未配置wxSDK,无法直接使用openLocation,所以将经纬度传给小程序,map页面为跳转中间页,再实现打开地图页面。h5://高德地图导航constaMapNavigate=(address,lng,lat)=>{......
  • 猪场管理APP开发功能有哪些
    猪场管理APP开发功能包括以下方面:智能监控功能:实时监控猪场情况,包括猪的数量、健康状况、采食量等信息,以便管理人员及时了解猪场情况,制定合理的养殖计划。自动控制功能:根据猪场环境异常情况,自动打开通风扇、通风口、湿帘、供暖等设备,以便及时恢复猪场环境。环境检测功能:......
  • 畜牧业APP开发要考虑哪些因素?
    畜牧业管理APP开发是一个复杂的过程,需要考虑多个方面的因素。以下是一些可能需要考虑的方面:用户需求:首先需要了解用户的需求,包括他们的目标、需求和期望。这将有助于确定应用程序的功能和界面设计。技术选择:选择适当的技术来开发畜牧业管理APP。例如,可以使用Java、Python、C......
  • 畜牧业管理APP开发功能
    畜牧业管理APP开发功能包括以下方面:禽畜监测:监测禽畜的生长状态、健康状况、采食量、体重等信息,以便管理人员及时了解禽畜的生长情况,制定合理的饲养计划。数据分析:对禽畜的生长数据、健康数据等进行分析,以便管理人员了解禽畜的生长情况,及时发现问题并采取措施。智能控制:......
  • Flutter/React native/un-app
    Flutter是Google开源的构建用户界面(UI)工具包,帮助开发者通过一套代码库高效构建多平台精美应用,支持移动、Web、桌面和嵌入式平台。[5] Flutter开源、免费,拥有宽松的开源协议,适合商业项目。Flutter可以方便的加入现有的工程中。在全世界,Flutter正在被越来越多的开发者和组织使......
  • 笨办法学 Python · 续 练习 11:`uniq`
    练习11:uniq原文:Exercise11:uniq译者:飞龙协议:CCBY-NC-SA4.0自豪地采用谷歌翻译在最后两个练习的开始,没有什么可说的了。你应该知道如何思考你的工作环境,你如何开始,你如何坐下来,影响你开始的任何事情。你也应该使用这些小小的45分钟的项目,突破了起始状态。如果你还没有弄清楚......
  • uniapp 使用vconsole
    1、安装vconsolenpminstallvconsole2、引用vconsole,找到main.js文件中,加上以下代码(区分环境):if(process.env.H_NODE_ENV!=='production'){ constvconsole=require('vconsole') Vue.prototype.$vconsole=newvconsole()}3、效果: ......
  • App Cleaner Uninstaller MacOS分析
    安装之后,直接使用HopperDisassembler打开,接着搜索"isunlock",你可以找到这个函数:[_TtC13App_Cleaner_822BaseFeaturesControllerisUnlocked]   这个函数从LicenseStateStroage中获取注册状态,它是LicenseManager的一个字段,偏移是:objc_ivar_offset__TtC13App_Cleane......