Vue json编辑器之bin-code-editor的使用

目录
文章目录隐藏
  1. bin-code-editor
  2. vue-json-editor 使用
  3. 总结

最近在做一个 vue 后台项目,需要一个 json 编辑器,要求能够格式化 json 数据,同时也支持编辑功能。搜搜索索一堆发现 bin-code-editor 插件就可以实现这个功能,话不多说,搞起来。

bin-code-editor

代码编辑器组件,0.1.0 版本默认只支持 json 代码,后期再进行扩展。

npm 安装

推荐使用 npm 安装,它能更好地和 webpack 打包工具配合使用。而且可以更好的和 es6 配合使用。并且支持按需引入

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

引入

在 main.js 中写入 2 行

import Vue from 'vue';
import CodeEditor from 'bin-code-editor';
import 'bin-code-editor/lib/styles/index.css';
import App from './App.vue';

Vue.use(CodeEditor);

new Vue({
  el: '#app',
  render: h => h(App)
});

test.vue 文件

<template>
  <div style="width: 70%;margin-left: 30px;margin-top: 30px;">
    <b-code-editor v-model="jsonStr" :auto-format="true" :smart-indent="true" theme="dracula" :indent-unit="4" :line-wrap="false" ref="editor"></b-code-editor>
    <br>
    <el-button type="primary" @click="onSubumit">提交</el-button>
  </div>
</template>

<script>
  const jsonData =`{
    "employees": [{
      "firstName": "Bill",
      "lastName": "Gates"
    }, {
      "firstName": "George",
      "lastName": "Bush"
    }, {
      "firstName": "Thomas",
      "lastName": "Carter"
    }]
  }`
  export default {
    data() {
      return {
        jsonStr:jsonData
      }
    },
    methods: {
      // 检测 json 格式
      isJSON(str) {
        if (typeof str == 'string') {
          try {
            var obj=JSON.parse(str);
            if(typeof obj == 'object' && obj ){
              return true;
            }else{
              return false;
            }

          } catch(e) {
            return false;
          }
        }else if (typeof str == 'object'  && str) {
          return true;
        }
      },
      onSubumit(){
        if (!this.isJSON(this.jsonStr)){
          this.$message.error(`json 格式错误`)
          return false
        }
        this.$message.success('json 格式正确')
      }
    }
  }
</script>
<style>

</style>

访问测试页面,效果如下:

Vue json 编辑器之 bin-code-editor 的使用

输入错误的值,点击执行,会有提示:

Vue json 编辑器之 bin-code-editor 的使用

详细内容官网查看:开发文档 | GITHUB

另外也在网上找到另一个 json 插件叫 vue-json-editor ,也可以实现对 json 的展示与校验,下面我们来看看对它的使用方法。

vue-json-editor 使用

npm 安装

npm install vue-json-editor -S

使用

test.vue 文件:

<template>
  <div style="width: 70%;margin-left: 30px;margin-top: 30px;">
    <vue-json-editor
      v-model="resultInfo"
      :showBtns="false"
      :mode="'code'"
     
      @json-change="onJsonChange"
      @json-save="onJsonSave"
      @has-error="onError"
    />
    <br>
    <el-button type="primary" @click="checkJson">确定</el-button>
  </div>
</template>

<script>
  // 导入模块
  import vueJsonEditor from 'vue-json-editor'

  export default {
    // 注册组件
    components: { vueJsonEditor },
    data() {
      return {
        hasJsonFlag:true,  // json 是否验证通过
        // json 数据
        resultInfo: {
          'employees': [
            {
            'firstName': 'Bill',
            'lastName': 'Gates'
            },
            {
              'firstName': 'George',
              'lastName': 'Bush'
            },
            {
              'firstName': 'Thomas',
              'lastName': 'Carter'
            }
          ]
        }
      }
    },
    mounted: function() {
    },
    methods: {
      onJsonChange (value) {
        // console.log('更改 value:', value);
        // 实时保存
        this.onJsonSave(value)
      },
      onJsonSave (value) {
        // console.log('保存 value:', value);
        this.resultInfo = value
        this.hasJsonFlag = true
      },
      onError(value) {
        // console.log("json 错误了 value:", value);
        this.hasJsonFlag = false
      },
      // 检查 json
      checkJson(){
        if (this.hasJsonFlag == false){
          // console.log("json 验证失败")
          // this.$message.error("json 验证失败")
          alert("json 验证失败")
          return false
        } else {
          // console.log("json 验证成功")
          // this.$message.success("json 验证成功")
          alert("json 验证成功")
          return true
        }
      },
    }
  }
</script>

<style>
</style>

插件参数说明:

<vue-json-editor
      v-model="resultInfo"  // 绑定数据 resultInfo
      :showBtns="false"  // 是否显示保存按钮
      :mode="'code'"  // 默认编辑模式
       // 显示中文,默认英文
      @json-change="onJsonChange"  // 数据改变事件
      @json-save="onJsonSave"  // 数据保存事件
      @has-error="onError"  // 数据错误事件
    />

相关说明:

  • resultInfo  默认绑定的变量,这个变量可以为空,编辑器会显示为{}
  • :showBtns 这里不显示保存按钮,为什么呢?原因有 2 个。1. 默认样式不好看。2. 只能当 json 数据正确,才能点击保存按钮,否则禁止点击。
  • json-changejson-savehas-error 这 3 个事件,是会实时触发的。

这里我额外加了一个检测方法,用来判断 json 数据是否正确。默认标记为 true,当不正确时,会改变状态为 false。

访问

点击确定,提示成功

vue-json-editor

改为错误的,点击确定,会提示失败。

vue-json-editor

注意:这个 json 编辑会带有下来菜单,实际项目中,需要去除,比较用户误操作。

在实际使用中发现几个问题:

  1. 输入中文时,传给后端的值不多;
  2. 输入大量 json 时,会有部分数据丢失。

因此,因此最终我们使用了 bin-code-editor 编辑器。

总结

以上就是自己在实际项目中测试使用的两个 vue 版的 json 插件心得,至于用哪一个,小伙伴们根据自己的实际需要来定,感谢阅读。

「点点赞赏,手留余香」

0

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » Vue json编辑器之bin-code-editor的使用

2 评论

  1. 引入vue3版本怎么使用 为什么显示空白

    1. 用的那个?是这个bin-code-editor吗?

发表回复