Vue3+TS封装全局字典函数

在Vue3中,我们可以通过provideinject来实现全局变量,但是对于全局字典而言,我们需要一个更加简单易用的封装。

以下是一个基于Vue3和TypeScript的全局字典函数封装示例:

interface Dictionary {
    
    
  [key: string]: string | number
}

const dictionary: Dictionary = {
    
    
  gender: {
    
    
    0: '女',
    1: '男',
    2: '保密'
  }
  // 其他字典项
}

export default function useDictionary() {
    
    
  return {
    
    
    getDictionary(key: string, value: string | number): string {
    
    
      const dict = dictionary[key]
      if (!dict) {
    
    
        return ''
      }
      return dict[value] || ''
    },
    setDictionary(key: string, dict: Dictionary): void {
    
    
      dictionary[key] = dict
    },
    deleteDictionary(key: string): void {
    
    
      delete dictionary[key]
    }
  }
}

以上代码中,我们定义了一个Dictionary接口用于存储各个字典项,具体的字典项可以根据实际需求进行添加或修改。在useDictionary函数中,我们返回了三个方法:getDictionary用于获取字典项的值,setDictionary用于设置字典项,deleteDictionary用于删除字典项。

使用该全局字典函数封装时,我们只需要在Vue3的setup函数中使用provide进行全局注入,然后在需要使用字典项的组件中使用inject来获取即可。

示例如下:

import {
    
     defineComponent, provide, inject } from 'vue'
import useDictionary from '@/utils/dictionary'

export default defineComponent({
    
    
  setup() {
    
    
    const dictionary = useDictionary()
    provide('dictionary', dictionary)

    return {
    
    
      // setup函数返回值
    }
  },
  methods: {
    
    
    getGenderLabel(gender: number): string {
    
    
      const dictionary = inject('dictionary')
      return dictionary.getDictionary('gender', gender)
    }
    // 其他方法
  }
})

以上代码中,我们在组件的setup函数中使用provide将全局字典函数注入到Vue3中,然后在组件的方法中使用inject来获取字典函数并调用getDictionary方法获取字典项的值。

通过以上的封装,我们可以在Vue3中轻松地实现全局字典的存取,提高代码的可读性和可维护性。

猜你喜欢

转载自blog.csdn.net/qq_27244301/article/details/131454299