vue中dicts怎么使用
1.确定字典获取的接口
目录在 /src/api/index.js
// 根据字典类型查询字典数据信息
export function getDicts(dictType) {
return new Promise((resolve)=>{
resolve({
code: 200,
data: [{
dictCode: '选项1',
dictLabel: '黄金糕'
}, {
dictCode: '选项2',
dictLabel: '双皮奶'
}]
})
})
}
2.在公共的方法文件中提供一个类方法
目录在 /src/utils/Dict/Dict.js
import Vue from 'vue';
import { getDicts } from '../../api';
export default class Dict {
constructor(dict){
this.dict = dict;
}
async init(names, callback) {
if(names === undefined || name === null){
throw new Error('need Dict names')
}
names.forEach(n => {
Vue.set(this.dict.dictLabel, n, {})
Vue.set(this.dict, n, [])
getDicts(n).then(res=>{
this.dict[n].splice(0, 0, ...res.data)
res.data.forEach(d=>{
Vue.set(this.dict.dictLabel[n], d.dictCode, d.dictLabel)
})
})
});
callback()
}
}
3.添加Dict组件
目录在 /src/utils/Dict/index.js
import Dict from "./Dict";
//install 函数是 Vue.js 插件的标准入口。当你在 Vue 应用中使用 Vue.use(plugin) 时,Vue 会自动调用这个 install 函数。
//Vue.mixin 用于全局混入一些选项(如 data、created 等生命周期钩子),这样所有的 Vue 组件都会继承这些选项
//当前的dict响应数据会继承到所有的Vue组件中,所有的Vue组件也会触发当前的created方法
const install = function(Vue){
Vue.mixin({
data(){
if(this.$options.dicts instanceof Array){
const dict = {
dict: {},
dictLabel: {},
}
return {
dict
}
}
return {}
},
created() {
if(this.$options.dicts instanceof Array) {
//Dict类方法中的initiate方法调用,接收两个参数
//第一个参数为组件的dicts配置项(dicts: ['myDicts']);
//第二个参数为回调函数,处理完字典数据时调用,使用 this.$nextTick 确保 DOM 更新完成后,再触发 dictReady 事件,通知父组件字典数据已经准备好。
new Dict(this.dict).init(this.$options.dicts, ()=>{
this.$nextTick(()=>{
this.$emit('dictReady')
})
})
}
}
})
}
export default { install }
4.在main.js中挂载
import dict from './utils/Dict'
Vue.use(dict)
5.在需要下拉字典数据的组件中使用
<template>
<div>
<el-select v-model="value" placeholder="请选择">
<el-option
v-for="item in dict.myDicts"
:key="item.dictCode"
:label="item.dictLabel"
:value="item.dictCode"
>
</el-option>
</el-select>
</div>
</template>
<script>
export default {
name: "HelloWorld",
dicts: ['myDicts'],
data() {
return {};
},
created(){
console.log(this.dict)
}
};
</script>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通