1.定义全局函数
utils/convert.js
function convertToChinese(value, type) {
// 定义选项对象,从缓存中获取并解析
const options = {
emdegree: uni.getStorageSync('emdegree'), // 学历
emdegreeisfull: uni.getStorageSync('emdegreeisfull'), // 是否全日制
empolitics: uni.getStorageSync('empolitics'), // 政治面貌
};
// 根据传入的 type 获取对应的选项
const selectedOptions = options[type];
if (!selectedOptions) {
return value;
}
// 遍历选项,查找匹配的值并返回对应的标签
for (let i = 0; i < selectedOptions.length; i++) {
if (selectedOptions[i].dictValue === value) {
return selectedOptions[i].dictLabel;
}
}
// 如果没有匹配的选项,则返回原始值
return value;
}
// 导出 convertToChinese 方法
module.exports = {
convertToChinese: convertToChinese
}
main.js
const convert = require('./utils/convert');//字典值转换
Vue.prototype.$convert = convert;
2.查询字典,存入缓存
//获取字典类型
getDict(){
this.$request(this.$host + "接口").then(res => {
uni.setStorage({
key: 'emdegree',
data: res.data,
});
})
}
3.页面
modify.vue
后端返回1,1对应大专进行显示
<view class="modifyBox_2">
<text class="text_1">学历</text>
<view class="inputName" @click="choiceDegree" v-model="userinfo.degree">
//在这里调用全局函数进行转换
<text>{{this.$convert.convertToChinese(userinfo.degree,"emdegree")?this.$convert.convertToChinese(userinfo.degree,"emdegree"):'-'}}</text>
<uni-icons type="compose" color="#3585F7" size="20"></uni-icons>
</view>
</view>
4.取出缓存值的label形成数组,赋给uni.showActionSheet
onShow() {
const emDegree=uni.getStorageSync('emdegree')
for (let i = 0; i < emDegree.length; i++) {
this.emdegreeList.push(emDegree[i].dictLabel)
}
},
choiceDegree() {
var that = this; //保存this
uni.showActionSheet({
itemList: this.emdegreeList,//上面缓存中取出的label
success(res) {
const emDegree=uni.getStorageSync('emdegree')
that.userinfo.degree=that.emdegreeList[res.tapIndex];//选中的lable付给缓存中的userinfo
const itemValue=that.mapData(that.emdegreeList[res.tapIndex], 'dictLabel', 'dictValue',emDegree); //调用这个函数确定选中label对应的value
that.$request(that.$host + "接口", {
degree: itemValue,//label对应的value
}, 'PUT').then(res => {
if (res.code == 200) {
uni.setStorageSync('userinfo', that.userinfo);//更新缓存
}
})
},
fail(res) {
console.log(res.errMsg);
}
});
}
mapData(data, labelKey, valueKey, targetObj) {
// data为选项数组中选中的label值,targetObj缓存中数组,labelKey, valueKey为targetObj的字段名
const targetValue = targetObj.find(item => item[labelKey] === data);
if (targetValue) {
// 找到匹配的目标值
return targetValue[valueKey]
}
},