共计 2368 个字符,预计需要花费 6 分钟才能阅读完成。
1. 安装
使用 npm:
$ npm install vue-json-viewer@2 --save
// Vue2
$ npm install vue-json-viewer@3 --save
// Vue3
使用 yarm:
$ yarn add vue-json-viewer@2
// Vue2
$ yarn add vue-json-viewer@3
// Vue3
使用 pnpm 也可以
2. 使用方法
在 main.ts 中注册插件
import { createApp } from 'vue';
import JsonViewer from 'vue-json-viewer'
import App from './App.vue';
const app = createApp(App);
app.use(JsonViewer )
app.mount('#app');
在界面中使用
template>
json-viewer
:value="data"
:expand-depth="5"
copyable
boxed
sort
class="w-100%">json-viewer>
template>
script setup lang="ts">
const data = {
total: 25,
limit: 10,
data: [
{
id: '5968fcad629fa84ab65a5247',
firstname: 'Ada',
lastname: 'Lovelace',
},
],
};
script>
注意 :在 main.ts 文件中可能会出现以下得 ts 类型报错:
无法找到模块“vue-json-viewer”的声明文件。
解决方法:
- 先尝试安装
npm i --save-dev @types/vue-json-viewer
- 如果上面方法不行,在全局的
.d.ts
结尾的文件中添加上declare module 'vue-json-viewer'
3. json-viewer 属性和方法
json-viewer 属性:
json-viewer 事件监听:
json-viewer 插槽:
json-viewer 快捷键:
4. 表格中原始数据和格式化数据切换
实现:给表格中每行数据单独添加一个变量,用于单独控制展示的方式。
state.tableData.forEach((item) => {
item.showJsonView = false;
});
template #default="scope">
div v-if="col.key ==='accountConfig'">
el-link
type="primary"
:underline="false"
@click="() => (scope.row.showJsonView = !scope.row.showJsonView)">
{{scope.row.showJsonView ? '原始数据' : '格式化数据'}}
el-link>
div v-if="scope.row.showJsonView">
json-viewer
:value="JSON.parse(scope.row[col.key])"
:expand-depth="1"
copyable>json-viewer>
div>
div v-else>
pre class="text-pre-wrap">{{scope.row[col.key] }}pre>
div>
div>
div v-else>
{{scope.row[col.key] }}
div>
template>
注:如果表格中有el-switch
, 单独控制每行的操作,请求时显示的loading
,也是同样的方法实现。
5. 自定义主题:
- 添加
theme="my-awesome-json-theme"
到 JsonViewer 的组件属性上 - 复制粘贴下面的模板并且根据自定义的 theme 名称做对应调整。
// values are default one from jv-light template
.my-awesome-json-theme {
background: #fff;
white-space: nowrap;
color: #525252;
font-size: 14px;
font-family: Consolas, Menlo, Courier, monospace;
.jv-ellipsis {
color: #999;
background-color: #eee;
display: inline-block;
line-height: 0.9;
font-size: 0.9em;
padding: 0px 4px 2px 4px;
border-radius: 3px;
vertical-align: 2px;
cursor: pointer;
user-select: none;
}
.jv-button { color: #49b3ff }
.jv-key { color: #111111 }
.jv-item {
&.jv-array { color: #111111 }
&.jv-boolean { color: #fc1e70 }
&.jv-function { color: #067bca }
&.jv-number { color: #fc1e70 }
&.jv-number-float { color: #fc1e70 }
&.jv-number-integer { color: #fc1e70 }
&.jv-object { color: #111111 }
&.jv-undefined { color: #e08331 }
&.jv-string {
color: #42b983;
word-break: break-word;
white-space: normal;
}
}
.jv-code {
.jv-toggle {
&:before {
padding: 0px 2px;
border-radius: 2px;
}
&:hover {
&:before {
background: #eee;
}
}
}
}
}
原文地址: vue 中 json 格式化显示(vue-json-viewer)
正文完