@composy/dict-vue
@composy/dict-vue
@composy/dict-core 的 Vue 3 适配层。这个包不重复实现字典逻辑,只把同一个 DictManager
注入 Vue 应用、engine 容器和响应式 composables。
✨ 核心能力
createDictPlugin():原生 Vue plugin,注入provide/inject和$dictcreateDictEnginePlugin():复用 core engine plugin,并补充 Vue app 自动安装useDict():异步加载字典项,处理 loading、error、快速切换 code 的竞态和卸载取消useDictItem():响应式读取当前值对应的只读字典项useDictLabel():响应式读取当前值对应的 labeluseDictOptions():把字典快照映射为 Select/Radio/Checkbox 友好的 optionsuseDictManager():直接读取注入的 manager
useDictOptions(code, { flatten }) 的 flatten 支持普通布尔值、Ref 和 getter,默认值为
true;响应式值变化时会重新生成选项列表。
安装
pnpm add @composy/dict-vue
- peer 依赖:
vue ^3.5.32 @composy/dict-core会作为直接依赖自动安装,无需重复声明
Vue Plugin
import { createDictPlugin } from '@composy/dict-vue'
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
app.use(
createDictPlugin({
dicts: [
{
code: 'gender',
items: [
{ label: '男', value: 1 },
{ label: '女', value: 2 },
],
},
],
fetcher: async (code, { signal }) => {
const response = await fetch(`/api/dicts/${code}`, { signal })
return response.json()
},
})
)
app.mount('#app')
Composables
<script setup lang="ts">
import { useDict, useDictLabel, useDictOptions } from '@composy/dict-vue'
import { ref } from 'vue'
const currentValue = ref(1)
const dict = useDict('gender')
const label = useDictLabel('gender', currentValue)
const options = useDictOptions('gender')
// useDict 在组件卸载或 code 切换时只取消自己的等待;manager 仍保留共享请求
</script>
<template>
<select v-model="currentValue">
<option v-for="option in options" :key="String(option.value)" :value="option.value">
{{ option.label }}
</option>
</select>
<span v-if="dict.loading">加载中...</span>
<span v-else>{{ label }}</span>
</template>
Engine Plugin
import { createDictEnginePlugin } from '@composy/dict-vue'
import { createVueEngine } from '@composy/engine-vue'
import App from './App.vue'
const engine = createVueEngine({
app: { rootComponent: App },
plugins: [
createDictEnginePlugin({
fetcher: async (code, { signal }) => {
const response = await fetch(`/api/dicts/${code}`, { signal })
return response.json()
},
}),
],
})
await engine.mount('#app')
安装后,同一个 DictManager 会被:
- 注入到 Vue
provide/inject - 暴露为
app.config.globalProperties.$dict - 注册到 engine container
- 同步到
dictEngineStateKeys.manager和dictEngineStateKeys.codes
直接安装到 Vue App 时,默认每个 App 创建独立 manager,并在 app.unmount() 时恢复原有
$dict;显式传入 manager 的共享实例默认不会被销毁。Engine 插件在卸载时释放自身 service/state/API
lease,并只销毁自己拥有的 manager。
验证
pnpm type-check
pnpm lint:check
pnpm build
构建统一使用 @composy/builder + rolldown(配置位于
.ldesign/builder.config.ts);TypeScript 与 ESLint 配置也集中在
.ldesign/,根目录同名配置保留为兼容入口。产物包含
dist、es、esm、lib,并在 postbuild 阶段校验 exports 与 CDN 入口。
🔗 相关链接
- packages/dict/packages/core:框架无关字典核心(manager、快照、原生组件)
- packages/engine:框架无关 Engine 及其 core/vanilla/vue 子包
Related Packages
Version History
| Version | Released | Vue | License |
|---|---|---|---|
| 0.0.2 | 3.5.32 | MIT | |
| 0.0.1 | ^3.5.32 | MIT |