plugin/dictionary.ts
import { localStorage } from '@/utils/storage'
import { App, getCurrentInstance } from 'vue'
export default {
install(app: App) {
// 获取数据字典
app.config.globalProperties.$getDictOptions = (code: string) => {
code = code.toUpperCase()
const dictData = localStorage.get('dictData')
if (dictData && dictData[code]) {
return dictData[code].item
}
return []
}
/**
* 根据字典属性及key获取字典item name
* @param userType 字典属性
* @param code item code
*/
app.config.globalProperties.$transDictName = (userType: string, code: string) => {
userType = userType.toUpperCase()
let name = ''
const dictData = localStorage.get('dictData')
if (dictData && dictData[userType]) {
dictData[userType].item.forEach((item: { code: string; name: string }) => {
if (item.code == code) {
name = item.name
}
})
}
return name
}
app.config.globalProperties.$transName = (list: any[], fromKey: string, toKey: string, value: any) => {
let name = ''
list &&
list.forEach((item: any) => {
if (item[fromKey] === value) {
name = item[toKey]
}
})
return name
}
/**
* 将字符串数组转成以分隔符相连的字符串
*
* @param stringList 字符串数组
* @param separator 分隔符
* @returns
*/
app.config.globalProperties.$transList2String = (stringList: Array<string> | undefined, separator?: string) => {
let result = ''
separator = separator ? separator : '、'
if (stringList) {
result = stringList
.filter((v) => {
if (v) return v
})
.join(separator)
}
return result
}
/**
* 将dictCode对应的字典item的code列表转成name字符串
*
* @param dictCode 字典编码
* @param itemCodeList 字典项编码列表
* @returns
*/
app.config.globalProperties.$transDictCodeList2String = (dictCode: string, itemCodeList: Array<string> | undefined) => {
let result = ''
if (itemCodeList) {
result = itemCodeList
.map((item) => {
return getCurrentInstance()?.proxy?.$transDictName(dictCode, item)
})
.join('、')
}
return result
}
/**
* 将字符串数组前limit个字符串转成以分隔符(、)相连的字符串
*
* @param stringList 字符串数组
* @param limit 字符个数
* @returns
*/
app.config.globalProperties.$transList2StringLimit = (stringList: Array<string> | undefined, limit?: number) => {
limit = limit ? limit : 5
const separator = '、'
const suffix = ' ...'
let result = ''
if (stringList) {
result = stringList.slice(0, limit).join(separator) + (stringList.length > limit ? suffix : '')
}
return result
}
},
}
main.ts
import Dictionary from '@/plugin/dictionary'
// 注册全局组件
app.component('Pagination', Pagination)
.use(createPinia())
.use(router)
.use(Dictionary)
.use(ElementPlus, { locale })
.use(i18n)
.use(VXETable)
.component('QtTable', QtTable)
.mount('#app')