11<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+ />
38</template >
49
510<script setup lang="ts">
611import 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'
820import { debounce } from ' ../utils'
921import CodeMirror from ' ./codemirror'
1022import { injectKeyProps } from ' ../../src/types'
@@ -25,6 +37,11 @@ const emit = defineEmits<(e: 'change', value: string) => void>()
2537
2638const el = useTemplateRef (' container' )
2739const { autoResize, autoSave } = inject (injectKeyProps )!
40+ let editor: CodeMirror .Editor
41+
42+ const emitChangeEvent = () => {
43+ emit (' change' , editor .getValue ())
44+ }
2845
2946onMounted (() => {
3047 const addonOptions = props .readonly
@@ -37,7 +54,7 @@ onMounted(() => {
3754 keyMap: ' sublime' ,
3855 }
3956
40- const editor = CodeMirror (el .value ! , {
57+ editor = CodeMirror (el .value ! , {
4158 value: ' ' ,
4259 mode: props .mode ,
4360 readOnly: props .readonly ,
@@ -71,18 +88,16 @@ onMounted(() => {
7188 )
7289 }
7390
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 ))
8397 }
84- })
85- }
98+ },
99+ { immediate: true },
100+ )
86101})
87102 </script >
88103
0 commit comments