一、安装插件
直接看效果:json格式化
安装版本不宜过旧也不宜过新,针对vue3安装这个版本即可
yarn add vue-json-viewer;"dependencies": {"vue-json-viewer": "3",},
二、使用插件
<script>
import JsonViewer from "vue-json-viewer";
import "vue-json-viewer/style.css";
export default {components: {JsonViewer,},
}
</script>
注意的是,这里需要对绑定数据做一个类型校验,对不合法数据类型进行剔除,另外可以自定义格式化框内部的样式
详细实例:
<JsonViewer :style="{minHeight: mainRowHeight,maxHeight: mainRowHeight,overflow: 'auto',fontSize: `${fontSize}px`,fontWeight: fontWeight,}":boxed="false":sort="false":expanded="true":copyable="true":show-array-index="false":show-double-quotes="true"expand-depth="20":value="getJSON()" ></JsonViewer><script>import JsonViewer from "vue-json-viewer";
import "vue-json-viewer/style.css";//引入插件样式
export default {components: {JsonViewer,},data(){return{ jsonValue:"",fontSize:“”,fontWeight:"",mainRowHeight:"",}},methods:{getJSON() {if (typeof this.jsonValue== "string") {try {var obj = JSON.parse(this.jsonValue);if (typeof obj == "object" && obj) {return obj;}} catch (e) {console.log("error:" + this.jsonValue+ "!!!" + e);return "";}} else {return this.jsonValue;}},}
}
<script>