Deng
Deng
vue3使用codemirror插件实现代码编辑器 | odjBlog
    欢迎来到odjBlog的博客!

vue3使用codemirror插件实现代码编辑器

技术总结及问题解决 odjbin 2年前 (2023-08-12) 58次浏览 0个评论

vue-codemirror 和 codemirror 的区别

vue-codemirror 和 codemirror 都可以在 Vue 3 中使用,将 CodeMirror 文本编辑器集成到你的 Vue.js 应用程序中。选择使用哪个取决于你的特定需求和偏好。

  • vue-codemirror:vue-codemirror 是一个 Vue.js 的包装组件,简化了在 Vue 应用程序中集成 CodeMirror 的过程。它以更符合 Vue 的方式在你的组件中使用 CodeMirror,通过将编辑器作为 Vue 组件暴露出来。这样可以更轻松地在 Vue 应用程序中管理编辑器的状态和行为,也可能更好地与 Vue 的响应性系统兼容。
  • codemirror:直接使用独立的 codemirror 库需要更多手动集成工作。你需要在 Vue 组件内直接管理 CodeMirror 实例,处理更新编辑器内容、管理事件以及与 Vue 的响应性系统集成等事项。

如果你重视 Vue 的响应性并且更喜欢更符合 Vue 思想的方法,那么 vue-codemirror 可能是一个更好的选择。它抽象了一些使用 CodeMirror 的复杂性,为你的 Vue 组件提供了更集成的体验。

另一方面,如果你有特定的需求或者想要更多地控制 CodeMirror 的集成和行为,你可能会选择直接使用 codemirror 库。

演示效果

版本说明

"codemirror": "^5.59.2",

安装 codemirror

npm install codemirror@5.59.2 --save

封装 codeEdit 组件完整代码

<template>
  <div class="codemirror-div">
    <textarea v-model="sqlVal" id="myCode"></textarea>
    <div class="sql-format">
      <span @click="formatSql">格式化 SQL</span>
      <span @click="clearVal">一键清空</span>
    </div>
  </div>
</template>
<script setup>
import CodeMirror from "codemirror/lib/codemirror"
import "codemirror/addon/edit/matchbrackets"
import "codemirror/addon/selection/active-line"
//需要什么语言,直接去 node_modules 中 codemirror/mode 里面找到去引入
import 'codemirror/mode/sql/sql.js'
import "codemirror/lib/codemirror.css";
// 替换主题这里需修改名称
import 'codemirror/theme/idea.css'
import "codemirror/theme/ambiance.css";
//代码补全提示
import "codemirror/addon/hint/show-hint.css";
import "codemirror/addon/hint/show-hint"
import "codemirror/addon/hint/sql-hint"
//SQL 代码格式化
import * as sqlFormatter from 'sql-formatter';

import {onMounted, defineEmits, defineProps} from "vue";

const emit = defineEmits(["input","changeTextarea","formatSql"])
const props = defineProps({
  editorLanguage: {
    type: String,
    default: 'text/x-sql'
  },
})
const sqlVal = ref('')
let editor = ref(null);
onMounted(() => {
  initEditor()
})
const initEditor = () => {
  editor = CodeMirror.fromTextArea(document.getElementById('myCode'), {
    mode: props.editorLanguage,//选择对应代码编辑器的语言,我这边选的是数据库,根据个人情况自行设置即可
    indentWithTabs: false, //在缩进时,是否需要把 n*tab 宽度个空格替换成 n 个 tab 字符,默认为 false
    tabSize: 2, // 缩进格式
    smartIndent: true,//自动缩进,设置是否根据上下文自动缩进(和上一行相同的缩进量)。默认为 true。
    lineNumbers: true,//是否在编辑器左侧显示行号。
    matchBrackets: true,// 匹配括号
    cursorHeight: 1, //光标高度。默认为 1,也就是撑满行高。对一些字体,设置 0.85 看起来会更好。
    lineWrapping: true,// 自动换行
    styleActiveLine: true, // 高亮选中行
    // readOnly: this.readOnly, //是否只读
    theme: 'idea',// 主题配置
    // autofocus: true,//是否在初始化时自动获取焦点。默认情况是关闭的。但是,在使用 textarea 并且没有明确指定值的时候会被自动设置为 true。
    extraKeys: {'Ctrl': 'autocomplete'},//自定义快捷键
    hintOptions: {//自定义提示选项
      // 当匹配只有一项的时候是否自动补全
      // completeSingle: false,
      tables: {
        users: ['name', 'score', 'birthDate'],
        countries: ['name', 'population', 'size']
      }
    }
  })
  let timeout
  editor.on('keyup', (cm, event) => {
    if (!cm.state.completeActive && ((event.keyCode >= 65 && event.keyCode <= 90) || event.keyCode === 52 || event.keyCode === 219 || event.keyCode === 190)) {
      CodeMirror.commands.autocomplete(cm, null, {
        completeSingle: false
      })
    }
    //加了一秒的防抖
    if (timeout) clearTimeout(timeout)
    timeout = setTimeout(() => {
      emit('change', editor.getValue())
    }, 1000)
  })
}
//代码格式化
const formatSql = () => {
  editor.setValue(sqlFormatter.format(editor.getValue()))
}
// 清除值
const clearVal = () => {
  editor.setValue('')
}
</script>
<style lang="scss" scoped>
.sql-format {
  background-color: #f7f7f7;
  text-align: right;
  color: #2a99ff;
  padding: 10px;

  span:hover {
    cursor: pointer;
    text-decoration: underline;
  }

  > span:first-child {
    margin-right: 10px;
  }
}
</style>

父组件调用组件 codeEdit

<template>
  <div class="code-editor">
    <code-edit  @change="changeSqlCode" :editor-language="'javascript'"/>
  </div>
</template>

<script setup>
 import CodeEdit from "@/components/codeEdit.vue";
 const sqlCode = ref();
  //实时获取 sql 语句
const changeSqlCode = (val) => {
   sqlCode.value = val
}
</script>

<style lang="scss" scoped>
.code-editor {
  border: 1px solid #b3b3b3;
  border-radius: 10px;
  overflow: hidden;
  margin-bottom: 10px;
}
</style>

这样我就在 vue3 中使用 codemirror 插件实现代码编辑器了..

喜欢 (0)
[]
分享 (0)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
已稳定运行:3年255天3小时55分