v-dict
TypeScript icon, indicating that this package has built-in type declarations

1.2.3 • Public • Published

Vue3 Dict Manager

Installation

npm i v-dict

Examples

dict.ts

import { createDictManager, defineDictData } from 'v-dict'

export const dm = createDictManager({
  // method to fetch remote dict
  fetch: (code) =>
    Promise.resolve([
      { label: 'xx', value: 'xx' },
      { label: 'xx', value: 'xx' }
    ]),
  // extra attr
  extra: ({ loadPromise, load, list, map, E }) => {
    return {
      getLabel: (value: string) => map[value]?.label
    }
  }
})

// same api for local dict or remote dict
// local
export const useStatusDict = dm.defineDict('STATUS', {
  data: defineDictData({
    ENABLED: {
      label: 'Enabled',
      // extra attr
      color: 'green'
    },
    DISABLED: {
      label: 'Disabled',
      color: 'red'
    }
  })
})
// remote
export const useRemoteStatusDict = dm.defineDict('REMOTE_STATUS', {
  remote: true,
  // overwrite dm fetch
  fetch: (code) =>
   // code = 'REMOTE_STATUS'
    Promise.resolve([
      { label: 'Enabled', value: 'ENABLED', color: 'green' },
      { label: 'Disabled', value: 'DISABLED' color: 'red' }
    ]),
  // merge dm extra
  extra: ({ loadPromise, load, list, map, E }) => {
    return {
      getItem: (value: string) => map[value]
    }
  }
})

// clear dict data
// dm.clear('REMOTE_STATUS')

// clear all dict data
// dm.clear()

xx.vue

<template>
  <div>
    {{ statusDict.E }}
    {{ statusDict.map }}
    {{ statusDict.list }}
    {{ statusDict.getLabel(statusDict.E.ENABLED) }}
    {{ statusDict.getItem(statusDict.E.DISABLED) }}
  </div>
</template>

<script setup lang="ts">
import { useRemoteStatusDict } from './dict'
import { onMounted } from 'vue'

const statusDict = useRemoteStatusDict({
  // Data sharing by default, independent data source when clone is true
  clone: true,
  // Whether the remote dictionary loads data immediately
  immediate: false,
  // whether to reload
  refresh: false
}) // statusDict is reactive!!!

const { E, map, list } = statusDict

/* 
E: {
  ENABLED: 'ENABLED',
  DISABLED: 'DISABLED'
}

map: {
  ENABLED: {
    label: 'Enabled',
    value: 'ENABLED',
    color: 'green'
  },
  DISABLED: {
    label: 'Disabled',
    value: 'DISABLED',
    color: 'red'
  }
}

list: [
  {
    label: 'Enabled',
    value: 'ENABLED',
    color: 'green'
  },
  {
    label: 'Disabled',
    value: 'DISABLED',
    color: 'red'
  }
]
*/

onMounted(async () => {
  await statusDict.load()

  await statusDict.loadPromise // immediate = true, using loadPromise to wait load
  // do after dict load
  console.log(statusDict.list)
  // clear dict data
  // statusDict.clear()
})
</script>

Readme

Keywords

Package Sidebar

Install

npm i v-dict

Weekly Downloads

10

Version

1.2.3

License

MIT

Unpacked Size

22.2 kB

Total Files

11

Last publish

Collaborators

  • rrryyi