likes
comments
collection
share

vue-json-pretty中自定义key的扩展

作者站长头像
站长
· 阅读数 55

背景

  • 在使用vue-json-pretty展示json数据时,有时候我们需要给特定的 key 加一些标注,对其进行一些扩展。
  • 如下面的需求:查询出来的json数据,对部分的key标注等级,并且点击标注会打开对应的一个页面

vue-json-pretty中自定义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 安装对应的依赖

vue-json-pretty中自定义key的扩展

使用方式

// 引入组件
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