背景

  • 在应用vue-json-pretty展现json数据时,有时候咱们须要给特定的 key 加一些标注,对其进行一些扩大。
  • 如上面的需要:查问进去的json数据,对局部的key标注等级,并且点击标注会关上对应的一个页面

批改计划

  • 对vue-json-pretty源码进行批改,采纳的1.7.1版本
  • 在src ---> components ---> app.vue中

    1. 第39到44行

      <span      v-if="currentDeep > 1 && !Array.isArray(parentData)"      class="vjs-key"      >    {{ prettyKey }}:</span>

      改为

      <span      v-if="currentDeep > 1 && !Array.isArray(parentData)"      class="vjs-key"      v-html="keyFormatter(prettyKey)"/>
    2. 第99到104行

       <span       v-if="parentData && currentKey && !Array.isArray(parentData)"       class="vjs-key"       >     {{ prettyKey }}:</span>

      改为

      <span      v-if="parentData && currentKey && !Array.isArray(parentData)"      class="vjs-key"      v-html="keyFormatter(prettyKey)"/>
    3. 在57到78行的 vue-json-pretty中增加一个办法

      :custom-key-formatter="customKeyFormatter"
    4. 在methods办法中增加keyFormatter

      keyFormatter (key) {    return this.customKeyFormatter        ? this.customKeyFormatter(key, this.path)    : `${key}:`},
    5. 在props中增加customKeyFormatter

      customKeyFormatter: {    type: Function,      default: null},
  • 以上改完后就能够通过 npm run build办法打包资源,打包资源前得先 npm i 装置对应的依赖

应用形式

// 引入组件import VueJsonPretty from '@/../public/changedNodeModules/vue-json-pretty';import 'vue-json-pretty/lib/styles.css';// 注册组件components: {    VueJsonPretty,}
<!-- 应用组件 --><VueJsonPretty :path="'res'" :data="executeResult" :custom-key-formatter="customKeyFormatter" />
  • executeResult 是 json数据 ;customKeyFormatter是对key自定的函数

    customKeyFormatter(key, path) {    // key 是须要自定义的 key;path是 key 对应的门路,到时打印进去就晓得了    // 有时候须要对path依据后盾给定的数据进行解决    const np = path.replace(/\[.*?]/g, '').replace(/^(res.)(hits.)+(_source.)+/g, '');    const l = this.leave[np];    if (l) {        const ll = l.split('@');        let color;        switch (ll[0]) {            case 'S1':                color = '#409eff';                break;            case 'S2':                color = '#e6a23c';                break;            case 'S3':            case 'S4':            case 'S5':                color = '#FF4949';                break;        }        // 依据门路自定义 key         return `${key}<a target="_blank" href="${ll[1]}" style="user-select:none;background: ${color};color: #fff; padding: 0 4px; font-weight: bolder">${ll[0]}</a> :`;    } else {        return key + ':';    }},
  • 具体应用文档请参考 vue-json-pretty