> 文章列表 > vue vue-json-viewer 展示 JSON 格式数据

vue vue-json-viewer 展示 JSON 格式数据

vue vue-json-viewer 展示 JSON 格式数据

1、下载 vue-json-viewer

npm 下载 vue-json-viewer

// Vue2
npm install vue-json-viewer@2 --save
// Vue3
npm install vue-json-viewer@3 --save

yarn 下载 vue-json-viewer

// Vue2
yarn add vue-json-viewer@2 
// Vue3
yarn add vue-json-viewer@3 

2、引入插件并注册

引入插件有两种方式:可以全局引入,也可以在单个页面文件中引入该插件。

2.1、全局注册组件

如果在全局 main.js 中引入,那么全局可用,无需在单独页面的 components 中注入 JsonViewer,可直接调用组件。具体实现:

main.js 文件中添加:

import JsonViewer from 'vue-json-viewer'
Vue.use(JsonViewer)

2.2、局部引入

如果在单页面中只需要引入 import JsonViewer from 'vue-json-viewer' ,然后在 components 中注入 JsonViewer 组件,即可正常使用。

具体实现:

// vue单页面文件中引入
<script>// 引入组件import JsonViewer from 'vue-json-viewer'export default {// 注册组件components:{JsonViewer}}
</script>

3、封装组件 JsonView

新建 JsonView.vue 文件:

<template><div><div v-show="showJson"><vue-json-viewer :value="jsonData" :expand-depth="expand"></vue-json-viewer></div><div v-show="!showJson">{{data}}</div></div>
</template><script>
import vueJsonViewer from 'vue-json-viewer'export default {name: '',data () {return {jsonData: this.data}},components: {vueJsonViewer},props: {showJson: {type: Boolean,default: true},data: {type: Object,default: () => {return {}}},// 展开层数expand: {type: Number,default: 2}},watch: {data () {this.jsonData = this.data}},computed: {},created () {},methods: {}
}
</script><style lang='less' module>
</style>

value 代表显示的 JSON 数据。

4、组件内使用

在需要使用的页面:

<template><div><json-view :data="jsonData"></json-view></div>
</template><script>
import jsonView from './components/JsonView.vue'
export default {name: '',components: {jsonView},data () {return {jsonData: {"name": "小明","age": 24,"gender": true,"height": 1.85,"weight": null,"skills": [{"PHP": ["Laravel","Composer"]},{"JavaScript": ["jQuery","Vue","React"]},"Golang","Python","Lua"]}}},methods: {}
}
</script><style lang=''>
</style>

页面效果:
vue vue-json-viewer 展示 JSON 格式数据

5、插件可选配置说明

属性 说明 类型 默认值
json 传入的json数据(必填) Object -
closed 是否折叠全部 Boolean false
deep 展开深度,越大渲染速度越慢,建议不超过5) Number 3
icon-style 折叠按钮样式,可选值为 [square, circle, triangle ] String square
icon-color 两个折叠按钮的颜色 Array theme = vs-code 时,[’#c6c6c6’, ‘#c6c6c6’],其他情况为 [’#747983’, ‘#747983’]
theme 可选主题样式,可选值为 [one-dark, vs-code], 不选时为默认的白色主题 String -
font-size 字体大小,单位 px Number 14
line-height 行高,单位 px Number 24

注:行高和字体大小不建议选用过大值,因为 icon 大小、每行的 padding-left 等参数并不会随之发生改变。