VUE中使用codemirror高亮显示代码

需求:

      项目中要实现在线浏览代码功能,选择使用codemirror,这里使用了一个别人封装ue-codemirror插件

1.安装

npm install vue-codemirror --save

2.在组件中引用

<codemirror :value="fileContent" :options="cmOptions"></codemirror>
//引入vue-codemirror
import { codemirror } from 'vue-codemirror';
//codeMirror核心样式
import 'codemirror/lib/codemirror.css';
//不同语言对应的不同高亮js,vue中使用无法直接加载,只好在组件中再次引入,想要设置哪些高亮就添加对应mode的js文件
require("codemirror/mode/clike/clike.js")
require("codemirror/mode/javascript/javascript.js")
require("codemirror/mode/xml/xml.js")
require("codemirror/mode/vue/vue.js")
require("codemirror/mode/python/python.js")
require("codemirror/mode/css/css.js")
require("codemirror/mode/sql/sql.js")
require("codemirror/mode/shell/shell.js")
data() {
    return {
      //要显示的代码,这里是从后台查询获得,目前初始化就先写空字符串了
      fileContent: '',
      cmOptions: {
        lineNumbers: true,
        matchBrackets: true,
        readOnly:true,
        //mode参数控制那种语言高亮,默认写的Java,mode具体怎么写,可以查看codemirror官网
        mode: 'text/x-java',
        tabSize: 4,
        line: true
      }
    };
  },

3.查询数据,根据文件后缀名设置mode的值,设置了主要几个语言,可以根据自己情况进行设置

//处理莫得值,根据文件名后缀
if (this.$utils.endWith(filePath, '.xml') || this.$utils.endWith(filePath, '.XML') || this.$utils.endWith(filePath, '.html')) {
  this.cmOptions.mode = 'text/html';
} else if (this.$utils.endWith(filePath, '.js') || this.$utils.endWith(filePath, '.JS')) {
  this.cmOptions.mode = 'text/javascript';
} else if (this.$utils.endWith(filePath, '.vue') || this.$utils.endWith(filePath, '.VUE')) {
  this.cmOptions.mode = 'text/x-vue';
} else if (this.$utils.endWith(filePath, '.css') || this.$utils.endWith(filePath, '.CSS')) {
  this.cmOptions.mode = 'text/css';
} else if (this.$utils.endWith(filePath, '.py') || this.$utils.endWith(filePath, '.PY')) {
  this.cmOptions.mode = 'text/x-python';
} else if (this.$utils.endWith(filePath, '.go') || this.$utils.endWith(filePath, '.GO')) {
  this.cmOptions.mode = 'text/x-go';
} else if (this.$utils.endWith(filePath, '.cpp') || this.$utils.endWith(filePath, '.CPP')) {
  this.cmOptions.mode = 'text/x-c++src';
} else if (this.$utils.endWith(filePath, '.sql') || this.$utils.endWith(filePath, '.SQL')) {
  this.cmOptions.mode = 'text/x-sql';
} else if (this.$utils.endWith(filePath, '.sh') || this.$utils.endWith(filePath, '.SH')) {
  this.cmOptions.mode = 'text/x-sh';
} else {
  this.cmOptions.mode = 'text/x-java';
}

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你认识小汐吗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值