vue3集成jsoneditor

一、背景

之前在做录制回放平台的时候,需要前端展示子调用信息,子调用是一个请求列表数组结构,jsoneditor对数组的默认展示结构是[0].[1].[2]..的方式,为了达到如下的效果,必须用到 onNodeName的钩子函数,因此深入调研了下vue3如何集成jsoneditor

最后做出来的效果图 alt

onNodeName的参考文档 https://github.com/josdejong/jsoneditor/blob/master/docs/api.md alt

二、参考方案

json-editor-vue3 感谢这位老哥的方案,我看了下源码,没有满足我的需要,核心就是属性需要自己加,因此我拿着他的代码改了下

三、代码实现

  • 安装依赖 jsoneditor
npm install --save jsoneditor

jsoneditor是个开源的js的组件,参考文档 https://github.com/josdejong/jsoneditor

  • 编写组件

目录结构如下 alt

vue3-json-editor.tsx: 其中options的定义是完全参考jsoneditor的api文档的,具体需要什么功能,自己去实现对应的options即可!

import { ComponentPublicInstance, defineComponent, getCurrentInstance, onMounted, reactive, watch } from 'vue'
// @ts-ignore
// eslint-disable-next-line import/extensions
import JsonEditor from 'jsoneditor';
import 'jsoneditor/dist/jsoneditor.min.css';
// eslint-disable-next-line import/prefer-default-export
export const Vue3JsonEditor = defineComponent({
  props: {
    modelValue: [StringBooleanObjectArray],
    showBtns: [Boolean],
    expandedOnStart: {
      typeBoolean,
      defaultfalse
    },
    navigationBar: {
      typeBoolean,
      defaulttrue
    },
    mode: {
      typeString,
      default'tree'
    },
    modes: {
      typeArray,
      default () {
        return ['tree''code''form''text''view']
      }
    },
    lang: {
      typeString,
      default'en'
    },
    onNodeName: {
      typeFunction,
      default()=>{}
    }
  },
  setup (props: any, { emit }) {
    const root = getCurrentInstance()?.root.proxy as ComponentPublicInstance

    const state = reactive({
      editornull as any,
      errorfalse,
      json: {},
      internalChangefalse,
      expandedModes: ['tree''view''form'],

      uid`jsoneditor-vue-${getCurrentInstance()?.uid}`
    })

    watch(
      () => props.modelValue as unknown as any,
      async (val) => {
        if (!state.internalChange) {
          state.json = val
          // eslint-disable-next-line no-use-before-define
          await setEditor(val)
          state.error = false
          // eslint-disable-next-line no-use-before-define
          expandAll()
        }
      }, { immediatetrue })

    onMounted(() => {
      //这个options的定义是完全参考jsoneditor的api文档的
      const options = {
        mode: props.mode,
        modes: props.modes,
        onChange () {
          try {
            const json = state.editor.get()
            state.json = json
            state.error = false
            // eslint-disable-next-line vue/custom-event-name-casing
            emit('json-change', json)
            state.internalChange = true
            emit('input', json)
            root.$nextTick(function ({
              state.internalChange = false
            })
          } catch (e) {
            state.error = true
            // eslint-disable-next-line vue/custom-event-name-casing
            emit('has-error', e)
          }
        },
        onNodeName(v: object) {
          // eslint-disable-next-line vue/custom-event-name-casing
            return props.onNodeName(v);
        },

        onModeChange () {
          // eslint-disable-next-line no-use-before-define
          expandAll()
        },
        navigationBar: props.navigationBar
      }
      state.editor = new JsonEditor(
        document.querySelector(`#${state.uid}`),
        options,
        state.json
      )

      // eslint-disable-next-line vue/custom-event-name-casing
      emit('provide-editor', state.editor)
    })

    function expandAll ({
      if (props.expandedOnStart && state.expandedModes.includes(props.mode)) {
        (state.editor as any).expandAll()
      }
    }

    function onSave ({
      // eslint-disable-next-line vue/custom-event-name-casing
      emit('json-save', state.json)
    }

    function setEditor (value: any): void {
      if (state.editor) state.editor.set(value)
    }

    return () => {
      // @ts-ignore
      // @ts-ignore
      return (
        <div>
          <div id={state.uid} class={'jsoneditor-vue'}></div>
        </div>

      )
    }
  }
})

style.css

.ace_line_group {
  text-align: left;
}
.json-editor-container {
  display: flex;
  width100%;
}
.json-editor-container .tree-mode {
  width50%;
}
.json-editor-container .code-mode {
  flex-grow1;
}
.jsoneditor-btns {
  text-align: center;
  margin-top10px;
}
.jsoneditor-vue .jsoneditor-outer {
  min-height150px;
}
.jsoneditor-vue div.jsoneditor-tree {
  min-height350px;
}
.json-save-btn {
  background-color#20a0ff;
  border: none;
  color#fff;
  padding5px 10px;
  border-radius5px;
  cursor: pointer;
}
.json-save-btn:focus {
  outline: none;
}
.json-save-btn[disabled] {
  background-color#1d8ce0;
  cursor: not-allowed;
}
code {
  background-color#f5f5f5;
}

index.ts

export * from './vue3-json-editor';

四、如何使用

<template>
  <div class="container">
    <Vue3JsonEditor
        v-model="json"
        mode='view'
        :show-btns="true"
        :on-node-name="onNodeName"
    />
  </div>
</
template>

<script lang="ts" setup>
import {computed,} from 'vue'
import {Vue3JsonEditor} from "@/components/json-editor";


const props = defineProps({
  record: {
    typeObject,
    default() {
      return {
        request: undefined,
      };
    },
  },
});

const json=computed(()=>{
  const {record} = props;
  return record.subInvocations;
});

// eslint-disable-next-line consistent-return
const onNodeName = (node: {
    value: anytypeany
})=>{
  if (node.type==='object' && node.value.identity) {
    return node.value.identity;
  }
  return undefined;
}

</script>

<script lang="ts">
export default {
  name: 'Invocations',
};
</
script>


<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}
</style>

本文由 mdnice 多平台发布

### 安装和配置编辑器于Vue 2项目 对于在Vue 2项目中安装和配置编辑器的需求,可以考虑使用`codemirror`或`monaco-editor`这类流行的代码编辑库。以下是基于`monaco-editor`的解决方案。 #### 使用Monaco Editor作为示例 为了简化集成过程,推荐采用`vue-monaco-editor-wrapper`这样的封装包来加速开发流程[^1]。 ##### 安装依赖项 通过npm或yarn安装必要的软件包: ```bash npm install monaco-editor vue-monaco-editor-wrapper --save ``` 或者如果偏好Yarn,则执行如下命令: ```bash yarn add monaco-editor vue-monaco-editor-wrapper ``` ##### 配置Vue应用 创建一个新的组件文件用于承载编辑器实例,在此假设命名为`EditorComponent.vue`并放置于`src/components/`目录下: ```html <template> <div id="editor"></div> </template> <script> import { defineComponent } from &#39;vue&#39;; import * as monaco from &#39;monaco-editor&#39;; export default defineComponent({ name: &#39;EditorComponent&#39;, mounted() { const editor = monaco.editor.create(this.$el, { value: &#39;// some comment\nconsole.log(\&#39;Hello world!\&#39;);&#39;, language: &#39;javascript&#39; }); } }); </script> <style scoped> #editor { height: 60vh; border: 1px solid grey; } </style> ``` 上述代码展示了如何初始化一个简单的JavaScript代码编辑环境,并设置了样式使得编辑区域具有一定的高度以及边框效果。 ##### 注册全局组件(可选) 为了让编辑器可以在整个应用程序范围内被访问到,可以选择将其注册成全局组件。这一步骤并非强制性的,取决于具体的应用场景需求。 在项目的入口文件(main.js)里加入下面几行代码完成全局注册操作: ```js // main.js import Vue from &#39;vue&#39;; import App from &#39;./App.vue&#39;; import EditorComponent from &#39;@/components/EditorComponent&#39;; // 调整路径适配实际位置 Vue.config.productionTip = false; new Vue({ render: h => h(App), }).$mount(&#39;#app&#39;); Vue.component(&#39;editor-component&#39;, EditorComponent); ``` 现在应该能够在任何地方利用标签 `<editor-component></editor-component>` 来引入这个自定义编辑器了。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值