vue 格式化JSON

发布时间 2023-12-09 09:30:06作者: 公子Learningcarer

第一步:安装

npm i bin-code-editor -S
# or 
yarn add bin-code-editor

第二步:在main.js中引入

//引入vue
import Vue from 'vue';

//引入bin-code-editor相关插件和样式
import CodeEditor from 'bin-code-editor';
import 'bin-code-editor/lib/styles/index.css';
//vue使用这个插件
Vue.use(CodeEditor);

第三步:在页面中使用

<template>
    <div class="json-container">
        <b-code-editor v-model="jsonStr" :theme="theme" :auto-format="false"
            ref="editor"
        :show-number="showNumber" :readonly="readonly" :lint="lint"/>

        <button @click="$refs['editor'].formatCode()">手动触发格式化</button>
    </div>
</template>

<script>
// 需要格式化的数据
const jsonData = `{"title":"测试json数据","children":[{"name":"子项名称", "desc":"子项说明" },{"name":"子项名称1", "desc":"子项说明1" }]}`

export default {
    name:'formatJson',
    data() {
        return {
            jsonStr: JSON.stringify(JSON.parse(jsonData),null,4),
            showNumber: true,
            lint: true,
            readonly: false,
            wrap: true,
            theme: 'idea'
        }
    }
}
</script>

<style scoped>
    /* 样式 */
    .json-container{
        width: 500px;
        height: 600px;
        text-align: left;
    }

</style>

效果图