CodeMirror踩坑

使用CodeMirror高亮显示js代码

首先封装在组件中

<template>

    <div class="json-editor">

        <textarea ref="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';

import "codemirror/theme/3024-day.css";

export default {

    name: 'JsonEditor',

    /* eslint-disable vue/require-prop-types */

    props: {

        value: String,

// 只读

        readOnly: {

            type: Boolean,

            defalut: false

        },

// 解析代码格式

        mode: {

            type: String,

            defalut: 'application/json'

        },

    },

    data() {

        return {

            jsonEditor: false

        };

    },

    watch: {

        value(value) {

            const editorValue = this.jsonEditor.getValue();

            if (value !== editorValue) {

                this.setModeValue();

            }

        }

    },

    mounted() {

        this.jsonEditor = CodeMirror.fromTextArea(this.$refs.textarea, {

            lineNumbers: true,

            mode: this.mode,

            gutters: ['CodeMirror-lint-markers'],

            theme: '3024-day',

            readOnly: this.readOnly,

            lint: true

        });

        if(this.value){

            this.setModeValue();

        }

        this.jsonEditor.on('change', (cm) => {

            this.$emit('changed', cm.getValue());

            this.$emit('input', cm.getValue());

        });

    },

    methods: {

        getValue() {

            if (this.jsonEditor.state.lint.marked.length > 0) {

                return false;

            }

            return this.jsonEditor.getValue();

        },

        // 根据不同mode取值,如果使用JSON.stringify解析字符串,文本框中会自动添加双引号

        setModeValue() {

            if(this.mode === "javascript") {

                this.jsonEditor.setValue(this.value);

            } else {

                this.jsonEditor.setValue(JSON.stringify(this.value, null, 2));

            }

        }

    }

};

</script>

<style lang="less" scoped>

.json-editor {

    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>

需要注册之后在子项目中使用

<VenusJsonEditor v-model="editForm.formula" mode="javascript" />

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值