vue中使用CodeMirror
# vue中使用CodeMirror
CodeMirror是一个基于iframe的可编辑源代码编辑器组件 ,它允许你创建类似相对舒适的源代码编辑器接口(代码内容包括HTML、XHTML、XML、CSS、Python、PHP、c#、Java标记以及其它类似的语言)。
# 安装
yarn add codemirror vue-codemirror
or
npm install codemirror vue-codemirror --save
1
2
3
2
3
根据实际需求,您可能需要安装更多的 CodeMirror 软件包
# CodeMirror languages...
yarn add @codemirror/lang-html
yarn add @codemirror/lang-json
yarn add @codemirror/lang-javascript
# CodeMirror themes...
yarn add @codemirror/theme-one-dark
# more CodeMirror packages...
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 示例代码
<template>
<codemirror
v-model="code"
placeholder="Code goes here..."
:style="{ height: '400px' }"
:autofocus="true"
:indent-with-tab="true"
:tab-size="2"
:extensions="extensions"
@ready="handleReady"
@change="log('change', $event)"
@focus="log('focus', $event)"
@blur="log('blur', $event)"
/>
</template>
<script>
import { defineComponent, ref, shallowRef } from 'vue'
import { Codemirror } from 'vue-codemirror'
import { javascript } from '@codemirror/lang-javascript'
import { oneDark } from '@codemirror/theme-one-dark'
export default defineComponent({
components: {
Codemirror
},
setup() {
const code = ref(`console.log('Hello, world!')`)
const extensions = [javascript(), oneDark]
// Codemirror EditorView instance ref
const view = shallowRef()
const handleReady = (payload) => {
view.value = payload.view
}
// Status is available at all times via Codemirror EditorView
const getCodemirrorStates = () => {
const state = view.value.state
const ranges = state.selection.ranges
const selected = ranges.reduce((r, range) => r + range.to - range.from, 0)
const cursor = ranges[0].anchor
const length = state.doc.length
const lines = state.doc.lines
// more state info ...
// return ...
}
return {
code,
extensions,
handleReady,
log: console.log
}
}
})
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
上次更新: 2023/05/09, 17:54:37