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>
相关推荐
是烟花哈3 小时前
【前端】React框架学习
前端·学习·react.js
qq4356947013 小时前
JavaWeb08
前端
2401_878454534 小时前
html和css的复习(1)
前端·css·html
@PHARAOH5 小时前
WHAT - git worktree 概念
前端·git
IT_陈寒5 小时前
我竟然被JavaScript的隐式类型转换坑了三天!
前端·人工智能·后端
我亚索贼六丶5 小时前
二十六. AI基础概念之如何更好的使用AI
前端
小码哥_常5 小时前
安卓启动页Logo适配秘籍:告别“奇形怪状”的展示
前端
我亚索贼六丶5 小时前
二十五.Electron 初体验与进阶
前端
当时只道寻常5 小时前
像使用 Redis 一样操作 LocalStorage
前端·前端工程化
RONIN5 小时前
UI组件库elementplus
前端