项目需要在线展示和编辑Json文件,所以需要找一个代码编辑器,因为我们的项目直接使用的 vueAdmin-template 这个模板
json编辑器也是直接从 vue-element-admin 项目扒下来的……
//好吧 这个项目看起来很炫,其实有很多坑,我们组没人用过vue,又需要快速完成任务,就随便找了一个= =
JsonEditor.vue(和原项目比我改了一下
<template> <div class="json-editor"> <textarea ref="textarea"></textarea> </div> </template> <script> import CodeMirror from ‘codemirror‘ import ‘codemirror/addon/lint/lint.css‘ import ‘codemirror/lib/codemirror.css‘ import ‘codemirror/theme/rubyblue.css‘ require(‘script-loader!jsonlint‘) import ‘codemirror/mode/javascript/javascript‘ import ‘codemirror/addon/lint/lint‘ import ‘codemirror/addon/lint/json-lint‘ export default { name: ‘jsonEditor‘, data() { return { jsonEditor: false } }, props: { value: String, changeFn: Function }, watch: { value(value) { const editor_value = this.jsonEditor.getValue() if (value !== editor_value) { this.jsonEditor.setValue(JSON.stringify(JSON.parse(this.value), null, 2)) } } }, mounted() { this.jsonEditor = CodeMirror.fromTextArea(this.$refs.textarea, { lineNumbers: true, mode: ‘application/json‘, gutters: [‘CodeMirror-lint-markers‘], theme: ‘rubyblue‘, lint: true }) // 将json文件格式化显示 this.jsonEditor.setValue(JSON.stringify(JSON.parse(this.value), null, 2)) // 当输入框内容发生变化 更新value值 this.jsonEditor.on(‘change‘, cm => { this.handleInput(cm) this.$emit(‘changed‘, cm.getValue()) this.$emit(‘input‘, cm.getValue()) }) }, methods: { getValue() { return this.jsonEditor.getValue() }, handleInput(e) { if (this.changeFn) { this.changeFn(e.getValue()) } } } } </script> <style> .CodeMirror { height: 100%; } .json-editor .cm-s-rubyblue span.cm-string { color: #F08047; } </style>
使用:
<json-editor :value="jsonData"></json-editor>
其中 jsonData 是json的字符串
开始的时候还在感叹好强大 但是随后,问题出现了……
第一个问题,一个页面有多个tab页,而json显示不在第一个tab页中,那么跳转到页面再点击json所在tab页……
嗯……默认显示不出来……
奇怪的事情是,当你点击一下,数据就出来了……更奇怪的事情是……甚至你拖一下开发者工具那个框,它也有可能就显示出来了,或者,你首先打开的tab也就是它,嗯,那也能显示出来……
对于这个问题,我选择了放弃,毕竟这可以解释为默认折叠的feature >_<
but,测试不听我解释并给我提出了个bug,还指出了一个更加丧病的bug……
如图,我把代码点开了,它竟然显示时这个shi样……(诡异的事情是,当行数变成10行以后它就显示正常了……
绝望……
更加绝望的事情是我百度了一年也没搜出来一点点相关信息……
无奈之下跑去找大神帮助。
总之最后解决的办法就是……
methods: { // ... refresh() { this.jsonEditor.refresh() } }
为 jsonEditor 加一个 refresh() 函数
并在每一次切换tab页的时候,都调用该组件的 refresh()
注意……不是直接调用……而是放入setTimeout中……
window.setTimeout(() => { this.$refs.jsonEditor1.refresh() this.$refs.jsonEditor2.refresh() })
我都已经双眼含泪了,不管怎样,问题终于得到解决了。
嗯……最后呢……解决办法……其实是:
autoRefresh: true
具体如下:
import ‘codemirror/addon/display/autorefresh‘ this.jsonEditor = CodeMirror.fromTextArea(this.$refs.textarea, { lineNumbers: true, mode: ‘application/json‘, gutters: [‘CodeMirror-lint-markers‘], theme: ‘rubyblue‘, lint: true, autoRefresh: true })
好了,现在没问题了,不用手动refresh了……
心好累啊
至于 autoRefresh 怎么实现的: https://codemirror.net/addon/display/autorefresh.js
自行参考吧。