vue3 使用 jsoneditor

vue3 使用 jsoneditor

在main.js中引入 样式文件

javascript 复制代码
import 'jsoneditor/dist/jsoneditor.css'

复制代码放到文件中就能用了

jsoneditor.vue

javascript 复制代码
<template>
    <div ref="jsonDom" style="width: 100%; height: 460px"></div>
</template>
<script setup lang="ts">
import { ref, onMounted, watchEffect } from 'vue'
import JsonEditor from 'jsoneditor'
interface validateResult {
    path: Array<string | number>
    message: string
}
const props = defineProps<{
    option: any
    validate?: (val: any) => validateResult
}>()
const emit = defineEmits(['update:modelValue', 'change', 'customValidation'])

const jsonDom = ref(null)
const validate = (res: any, editor: any) => {
    try {
        emit('change', {
            success: res.length === 0 && typeof editor.get() !== 'number',
            json: editor.getText()
        })
    } catch (error) {
        console.log(error)
    }
}
onMounted(() => {
    const options = {
        history: false,
        sortObjectKeys: false,
        mode: 'code',
        modes: ['code', 'text'],
        onChange() {
            editor.validate().then((res: any) => validate(res, editor))
        },
        onBlur() {
            try {
                editor.set(eval(`(${editor.getText()})`))
                editor.validate().then((res: any) => validate(res, editor))
            } catch (error) {
                console.log(error)
            }
        },
        onValidate: props.validate,
        onValidationError: function (errors: any) {
            errors.forEach((error: any) => {
                switch (error.type) {
                    case 'validation': // schema validation error
                        break
                    case 'customValidation': // custom validation error
                        emit('customValidation')
                        break
                    case 'error': // json parse error
                        emit('change', {
                            success: false,
                            json: editor.getText()
                        })
                        break
                }
            })
        }
    }
    const editor = new JsonEditor(jsonDom.value, options)
    watchEffect(() => {
        editor.set(props.option)
        editor.validate().then((res: any) => validate(res, editor))
    })
})
</script>
相关推荐
小鸡脚来咯7 分钟前
前端传输的数据格式的选择
java·开发语言·前端·后端
小二·12 分钟前
【万字源码级剖析】深入理解 Vue 3 响应式系统:ref、reactive、computed 与 effect 的底层实现
前端·javascript·vue.js
Mintopia19 分钟前
“开源”和“闭源“,AI 模型的发展方向
前端·人工智能·aigc
Mintopia21 分钟前
哈珀·李的《**杀死一只知更鸟**》(*To Kill a Mockingbird*)是一部关于**人性、正义与道德成长**的小说
前端
且菜且折腾32 分钟前
react快捷键hook
javascript·react.js·ecmascript
什么都不会的Tristan35 分钟前
Feed流(关注推送)
java·前端·数据库
IT_陈寒37 分钟前
Vite 5.0 性能优化实战:从3秒到300ms的构建提速秘籍
前端·人工智能·后端
一路向前的月光39 分钟前
前端采用electron-hiprint控件实现静默打印
前端·javascript·electron
Jagger_1 小时前
AI还原设计稿方法
前端
毛小茛1 小时前
pnpm 已经安装成功,但 npm 的全局 bin 目录没有进 PATH
前端·npm·node.js