当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 在vue项目中使用codemirror插件实现代码编辑器功能

在vue项目中使用codemirror插件实现代码编辑器功能

2019年09月06日  | 移动技术网IT编程  | 我要评论

在vue项目中使用codemirror插件实现代码编辑器功能(代码高亮显示及自动提示),具体内容如下所示:

1、使用npm安装依赖

npm install --save codemirror;

2、在页面中放入如下代码

<template>
 <textarea ref="mycode" class="codesql" v-model="code" style="height:200px;width:600px;"></textarea>
</template>
<script>
import "codemirror/theme/ambiance.css";
import "codemirror/lib/codemirror.css";
import "codemirror/addon/hint/show-hint.css";
let codemirror = require("codemirror/lib/codemirror");
require("codemirror/addon/edit/matchbrackets");
require("codemirror/addon/selection/active-line");
require("codemirror/mode/sql/sql");
require("codemirror/addon/hint/show-hint");
require("codemirror/addon/hint/sql-hint");
 export default {
   name: "codemirror",
  data () {
   return {
    code: '//按ctrl键进行代码提示'
   }
  },
  mounted () {
   debugger
   let mime = 'text/x-mariadb'
   //let theme = 'ambiance'//设置主题,不设置的会使用默认主题
   let editor = codemirror.fromtextarea(this.$refs.mycode, {
    mode: mime,//选择对应代码编辑器的语言,我这边选的是数据库,根据个人情况自行设置即可
    indentwithtabs: true,
    smartindent: true,
    linenumbers: true,
    matchbrackets: true,
    //theme: theme,
    // autofocus: true,
    extrakeys: {'ctrl': 'autocomplete'},//自定义快捷键
    hintoptions: {//自定义提示选项
     tables: {
      users: ['name', 'score', 'birthdate'],
      countries: ['name', 'population', 'size']
     }
    }
   })
   //代码自动提示功能,记住使用cursoractivity事件不要使用change事件,这是一个坑,那样页面直接会卡死
   editor.on('cursoractivity', function () {
    editor.showhint()
   })
  }
 }
</script>
<style>
.codesql {
  font-size: 11pt;
  font-family: consolas, menlo, monaco, lucida console, liberation mono, dejavu sans mono, bitstream vera sans mono, courier new, monospace, serif;
 }
</style>

3、话不多说,直接上图

总结

以上所述是小编给大家介绍的在vue项目中使用codemirror插件实现代码编辑器功能,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网