在项目有使用到代码编辑器的插件,所以找到codemirror
这个插件,在此记录一下codemirror
的使用方式
需要安装的插件有:
yarn add codemirror //这个不下会报错
yarn add vue-codemirror
yarn add @codemirror/lang-javascript @codemirror/theme-one-dark
使用代码
<template>
<div class="box">
<Codemirror
class="code"
v-model="code"
:style="{ height: '100%' }"
:extensions="extensions"
:autofocus="true"
:disabled="false"
@ready="handleClick('ready', $event)"
@change="handleClick('change', $event)"
@focus="handleClick('focus', $event)"
@blur="handleClick('blur', $event)"
/>
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { Codemirror } from "vue-codemirror";
import { javascript } from "@codemirror/lang-javascript";
import { oneDark } from "@codemirror/theme-one-dark";
const code = ref(`console.log('Hello, world!');console.log('Hello, world!');`);
const extensions = [javascript(), oneDark];
const handleClick = (type: string, val: Event) => {
console.log(type, val);
};
</script>
<style>
.box {
width: 100%;
height: 300px;
border: 1px solid #f00;
}
.code {
width: 300px;
height: 300px;
}
</style>
一般我们百度的时候都是用的JavaScript的语法做示例,但是当我们要切换语法的时候,这个时候就需要用到别的插件了
yarn add @codemirror/language @codemirror/legacy-modes
import { Empty } from 'ant-design-vue';
<template>
<div class="box">
<Codemirror
class="code"
v-model="code"
:style="{ height: '100%' }"
:extensions="extensions"
:autofocus="true"
:disabled="false"
@ready="handleClick('ready', $event)"
@change="handleClick('change', $event)"
@focus="handleClick('focus', $event)"
@blur="handleClick('blur', $event)"
/>
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { Codemirror } from "vue-codemirror";
import { javascript } from "@codemirror/lang-javascript";
import { oneDark } from "@codemirror/theme-one-dark";
import { StreamLanguage } from "@codemirror/language";
import { yaml } from "@codemirror/legacy-modes/mode/yaml";
const code = ref(``);
const extensions = [StreamLanguage.define(yaml), oneDark];
const handleClick = (type: string, val: Event) => {
console.log(type, val);
};
</script>
<style>
.box {
width: 100%;
height: 300px;
border: 1px solid #f00;
}
.code {
width: 300px;
height: 300px;
}
</style>
总的来说就是这样,下面是我看到的已有的高亮语法样式插件,可以参考一下
"@codemirror/commands": "^6.x",
"@codemirror/lang-cpp": "^6.x",
"@codemirror/lang-css": "^6.x",
"@codemirror/lang-html": "^6.x",
"@codemirror/lang-java": "^6.x",
"@codemirror/lang-javascript": "^6.x",
"@codemirror/lang-json": "^6.x",
"@codemirror/lang-lezer": "^6.x",
"@codemirror/lang-markdown": "^6.x",
"@codemirror/lang-php": "^6.x",
"@codemirror/lang-python": "^6.x",
"@codemirror/lang-rust": "^6.x",
"@codemirror/lang-sql": "^6.x",
"@codemirror/lang-xml": "^6.x",
"@codemirror/legacy-modes": "^6.x",
"@codemirror/theme-one-dark": "^6.x",
网友评论