vue-json-editor json編輯器


一、概述

現有一個vue項目,需要一個json編輯器,能夠格式化json數據,同時也支持編輯功能。

vue-json-editor 插件就可以實現這個功能

 

二、vue-json-editor 使用

安裝插件

npm install vue-json-editor --save

 

使用

test.vue

<template>
  <div style="width: 70%;margin-left: 30px;margin-top: 30px;">
    <vue-json-editor
      v-model="resultInfo"
      :showBtns="false"
      :mode="'code'"
      lang="zh"
      @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>
View Code

 

插件參數說明:

<vue-json-editor
      v-model="resultInfo"  // 綁定數據resultInfo
      :showBtns="false"  // 是否顯示保存按鈕
      :mode="'code'"  // 默認編輯模式
      lang="zh"  // 顯示中文,默認英文
      @json-change="onJsonChange"  // 數據改變事件
      @json-save="onJsonSave"  // 數據保存事件
      @has-error="onError"  // 數據錯誤事件
    />

相關說明:

resultInfo  默認綁定的變量,這個變量可以為空,編輯器會顯示為{}

:showBtns 這里不顯示保存按鈕,為什么呢?原因有2個。1. 默認樣式不好看。2. 只能當json數據正確,才能點擊保存按鈕,否則禁止點擊。

json-change,json-save,has-error 這3個事件,是會實時觸發的。

 

這里我額外加了一個檢測方法,用來判斷json數據是否正確。默認標記為true,當不正確時,會改變狀態為false。

 

訪問

點擊確定,提示成功

 

 

 改為錯誤的,點擊確定,會提示失敗。

 

注意:這個json編輯會帶有下來菜單,實際項目中,需要去除,比較用戶誤操作。

在實際使用中發現幾個問題:

1. 輸入中文時,傳給后端的值不多

2. 輸入大量json時,會有部分數據丟失。

因此,我們使用下面的編輯器bin-code-editor 

 

三、bin-code-editor

開發文檔 | GITHUB

安裝模塊

npm install bin-code-editor -d

 

引入

在 main.js 中寫入2行

import CodeEditor from 'bin-code-editor';
Vue.use(CodeEditor);

 

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>
View Code

 

訪問測試頁面,效果如下:

 

 

輸入錯誤的值,點擊執行,會有提示

 

 

 

本文參考鏈接:

https://blog.csdn.net/qq_41956789/article/details/104960794

https://juejin.cn/post/6844904106671210503

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM