赞
踩
目录
4.封装成公共组件,可直接使用,基于vue2,运行后按照提示npm下载包
使用的是vue-template-admin中的Json编辑器。目的是展示后端传过来的Json字符串数据。
拷贝admin项目中关于这个的.vue文件
npm下载对应的包
接下来可以注册为全局组件
暴露接口,通过:value传输数据给组件,就可以简单使用。
1.设置编辑器的样式之类的,需要再引用文件,在node_moudules里面找codemirror文件夹。
2.可以设置的地方很多,可以参考官网,列举一些常用属性:
mode: "text/groovy", //实现groovy代码高亮 mode: "text/x-java", //实现Java代码高亮 lineNumbers: true, //显示行号 theme: "dracula", //设置主题 lineWrapping: true, //代码折叠 foldGutter: true, gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], matchBrackets: true, //括号匹配 //readOnly: true, //只读3.除了使用对外暴露的接口外,还可以使用setvalue()方法去赋值
新建JsonEditor.vue文件,然后注册为全局组件:
- <template>
- <!-- 只需要传入数据即可使用:value -->
- <div class="json-editor">
- <textarea ref="textarea" />
- </div>
- </template>
- <style scoped>
- @import '../../../node_modules/codemirror/lib/codemirror.css';
- @import '../../../node_modules/codemirror/theme/dracula.css';
- @import '../../../node_modules/codemirror/addon/lint/lint.css';
- </style>
- <script>
- import CodeMirror from 'codemirror'
- import 'codemirror/mode/javascript/javascript'
- import 'codemirror/addon/lint/lint'
- import 'codemirror/addon/lint/json-lint'
- // eslint-disable-next-line import/no-webpack-loader-syntax
- require('script-loader!jsonlint')
-
- export default {
- name: 'JsonEditor',
- /* eslint-disable vue/require-prop-types */
- props: ['value'],
- data () {
- return {
- jsonEditor: false
- }
- },
- watch: {
- value (value) {
- const editorValue = this.jsonEditor.getValue()
- if (value !== editorValue) {
- this.jsonEditor.setValue(JSON.stringify(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,
- readOnly: true // 只读
- })
-
- this.jsonEditor.setValue(JSON.stringify(this.value, null, 2))
- this.jsonEditor.on('change', cm => {
- this.$emit('changed', cm.getValue())
- this.$emit('input', cm.getValue())
- })
- },
- methods: {
- getValue () {
- return this.jsonEditor.getValue()
- }
- }
- }
- </script>
-
- <style lang="scss" scoped>
- .json-editor {
- text-align-last: left;
- // width: 100%;
- // height: 100%;
- position: relative;
-
- ::v-deep {
- .CodeMirror {
- height: auto;
- min-height: 300px;
- }
-
- .CodeMirror-scroll {
- min-height: 300px;
- }
-
- .cm-s-rubyblue span.cm-string {
- color: #F08047;
- }
- }
- }
- </style>
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。