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>

posted @   天官赐福·  阅读(1073)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
返回顶端
点击右上角即可分享
微信分享提示