在vue中使用vkbeautify将xml、json格式化展示

3,563 阅读1分钟

项目中有个需求是实现报文展示,需要将xml、json格式化展示到页面上。

vkbeautify 是一个做格式化的工具,可以将xml、json字符串做格式化处理,处理后的字符串直接放入pre+code的标签就能显示格式化好的样子

  1. 首先先下载vkbeautify文件

    npm install vkbeautify

  2. 组件里,引入vkbeautify模块

    import vkbeautify from ‘vkbeautify’

  3. 格式化字符串方法:

    vkbeautify.xml(‘xxxxxxxxx’)

    vkbeautify.json(‘xxxxxxxxx’)

因为vkbeautify.json方法格式化会调用JSON.parse,需考虑处理json格式不规范的error,这里我封装了codeBox组件,用于格式化xml和json数据,其中对规范和不规范的json做了容错处理

<template>
    <Poptip class="code-box-container" placement="right" transfer :word-wrap="isString">
        <Icon class="outline_icon" type="md-list-box" />
        <template slot="content">
            <pre class="json-item" v-html="codeText" v-if="!isString&&type=='json'"></pre>
            <xmp v-else-if="!isString&&type=='xml'">{{codeText}}</xmp>
            <div v-else class="json-item string-box" v-html="codeText"></div>
        </template>
    </Poptip>
</template>
<script>
import vkbeautify from "vkbeautify";
export default {
  name: "codeBox",
  data() {
    return {
      codeText: "",
      isString: false // 若是无法识别的JSON 直接以字符串的方式展示
    };
  },
  //接收来自传递进来的参数
  props: {
    val: {
      type: String / Object, // val可以为JSON字符串 也可以为对象
      default: ""
    },
    type: {
      type: String, // 类型  xml or json
      default: "json"
    }
  },
  mounted() {
    this.funInit();
  },
  watch: {
    // 异步赋值
    val() {
      this.funInit();
    }
  },
  methods: {
    funInit() {
      if (!this.val) {
        this.codeText = "";
        this.isString = false;
      } else {
        if (this.type == "xml") {
          this.codeText = vkbeautify.xml(this.val);
        } else {
          this.codeText = this.jsonFormat(this.val);
        }
      }
    },
    jsonFormat(jsonTemp) {
      let json = "";
      try {
        // stringify 时需指定缩进否则不会显示换行。为了防止传入的string没有指定 在此统一执行一遍
        if (typeof jsonTemp != "string") {
          json = JSON.stringify(jsonTemp, undefined, 2);
        } else {
          json = JSON.stringify(JSON.parse(jsonTemp), undefined, 2);
        }
        let jsonObj = JSON.parse(json);
        if (typeof jsonObj === "object") {
          this.isString = false;
          return vkbeautify.json(jsonTemp);
        } else {
          this.isString = true;
          return jsonTemp;
        }
      } catch (e) {
        this.isString = true;
        return jsonTemp;
      }
    }
  }
};
</script>
<style scoped lang="less">
.code-box-container {
  .outline_icon {
    font-size: 16px;
    color: #2b85e4;
    cursor: pointer;
  }
}
</style>

组件使用:

<code-box :val="content" type="xml"></code-box>

效果展示:

image.png