Vue3中jsoneditor的使用示例详解

 更新时间:2024年01月11日 16:42:24   作者:Mrceel  
这篇文章主要为大家详细介绍了Vue3中jsoneditor的使用相关知识,文中的示例代码讲解详细,具有一定的学习价值,感兴趣的小伙伴可以跟随小编一起了解下

vue3 使用 jsoneditor

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

jsoneditor.vue

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

到此这篇关于Vue3中jsoneditor的使用示例详解的文章就介绍到这了,更多相关Vue3 jsoneditor内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:

相关文章

最新评论