1
1
<template >
2
- <div ref =" container" class =" editor" />
2
+ <div
3
+ ref =" container"
4
+ class =" editor"
5
+ @keydown.ctrl.s.prevent =" emitChangeEvent"
6
+ @keydown.meta.s.prevent =" emitChangeEvent"
7
+ />
3
8
</template >
4
9
5
10
<script setup lang="ts">
6
11
import type { ModeSpec , ModeSpecOptions } from ' codemirror'
7
- import { inject , onMounted , useTemplateRef , watchEffect } from ' vue'
12
+ import {
13
+ inject ,
14
+ onMounted ,
15
+ onWatcherCleanup ,
16
+ useTemplateRef ,
17
+ watch ,
18
+ watchEffect ,
19
+ } from ' vue'
8
20
import { debounce } from ' ../utils'
9
21
import CodeMirror from ' ./codemirror'
10
22
import { injectKeyProps } from ' ../../src/types'
@@ -25,6 +37,11 @@ const emit = defineEmits<(e: 'change', value: string) => void>()
25
37
26
38
const el = useTemplateRef (' container' )
27
39
const { autoResize, autoSave } = inject (injectKeyProps )!
40
+ let editor: CodeMirror .Editor
41
+
42
+ const emitChangeEvent = () => {
43
+ emit (' change' , editor .getValue ())
44
+ }
28
45
29
46
onMounted (() => {
30
47
const addonOptions = props .readonly
@@ -37,7 +54,7 @@ onMounted(() => {
37
54
keyMap: ' sublime' ,
38
55
}
39
56
40
- const editor = CodeMirror (el .value ! , {
57
+ editor = CodeMirror (el .value ! , {
41
58
value: ' ' ,
42
59
mode: props .mode ,
43
60
readOnly: props .readonly ,
@@ -71,18 +88,16 @@ onMounted(() => {
71
88
)
72
89
}
73
90
74
- if (autoSave .value ) {
75
- editor .on (' change' , () => {
76
- emit (' change' , editor .getValue ())
77
- })
78
- } else {
79
- el .value ! .addEventListener (' keydown' , (e : KeyboardEvent ) => {
80
- if (e .ctrlKey && e .key === ' s' ) {
81
- e .preventDefault ()
82
- emit (' change' , editor .getValue ())
91
+ watch (
92
+ autoSave ,
93
+ (autoSave ) => {
94
+ if (autoSave ) {
95
+ editor .on (' change' , emitChangeEvent )
96
+ onWatcherCleanup (() => editor .off (' change' , emitChangeEvent ))
83
97
}
84
- })
85
- }
98
+ },
99
+ { immediate: true },
100
+ )
86
101
})
87
102
</script >
88
103
0 commit comments