vue-json-editor 簡單實現


項目需求需要做個 json 編輯器,github json-editor star最高,地址如下 https://github.com/josdejong/jsoneditor ,這里面功能很多,項目需求就自己封裝一個組件,方便你我他。

main.js 中引入 后 掛載到 prototype

import jsoneditor from 'jsoneditor'
Vue.prototype.$jsoneditor = jsoneditor
 
那么在組件中直接可以拿到 jsoneditor 對象  進行操作了 
<template>
  <div>
    <div id="jsoneditor" style="width: 400px; height: 200px;"></div>
  </div>
</template>
 
<script>
export default {
  name: "JsonEditor",
  /* eslint-disable vue/require-prop-types */
  props: {
    value: {
      type: Object
    }
  },
  data() {
    return {
      jsonEditor: null
    };
  },
  watch: {
    value(value) {
      const editorValue = this.jsonEditor.get();
      if (value !== editorValue) {
        this.jsonEditor.set(value);
      }
    }
  },
  mounted() {
    this.initJsonEditor();
  },
  methods: {
    // 初始化jsonEditor
    initJsonEditor() {
      var container = document.getElementById("jsoneditor");
      var options = {
        mode: "tree"
      };
      var editor = new this.$jsoneditor(container, options);
      this.jsonEditor = editor;
    },
    // 獲取json
    getValue() {
      return this.jsonEditor.get();
    }
  }
};
</script>

接下來就是直接在組件中引入 

<JsonEditor :value="testdata"></JsonEditor> 

就能將組件的數據渲染到json editor 中

 


免責聲明!

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



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