Created
September 26, 2019 07:38
-
-
Save hauptbenutzer/dc0b894625f239b82b88244d5393b7d8 to your computer and use it in GitHub Desktop.
CodeMirror VueJS v-model binding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template lang="html"> | |
<div class="code-editor"> | |
<textarea ref="textarea"/> | |
</div> | |
</template> | |
<script> | |
import CodeMirror from 'codemirror/lib/codemirror.js' | |
import 'codemirror/mode/htmlmixed/htmlmixed.js' | |
// You'll also want to include the css files | |
export default { | |
props: { value: String }, | |
data: () => ({ | |
editor: null | |
}), | |
watch: { | |
value: { | |
handler (newVal) { | |
// Only set value in editor if it differs from current state. This avoids resetting the cursor position. | |
if (newVal && this.editor.getValue() !== newVal) { | |
this.editor.setValue(newVal) | |
// CodeMirror might need a refresh if a lot of content is changed. | |
this.$nextTick(() => this.editor.refresh()) | |
} | |
}, | |
immediate: true | |
} | |
}, | |
mounted () { | |
// Create CodeMirror instance from textarea DOM node. | |
this.editor = CodeMirror.fromTextArea(this.$refs.textarea, { | |
mode: 'htmlmixed', | |
lineNumbers: true, | |
theme: 'xq-light' | |
// ...other options | |
}) | |
// Emit `input` event on changes to implement `v-model`. | |
this.editor.on('change', () => { | |
this.$emit('input', this.editor.getValue()) | |
}) | |
}, | |
beforeDestroy () { | |
// Be sure to clean up after ourselves and destroy the CodeMirror instance | |
this.editor.toTextArea() | |
} | |
} | |
</script> | |
<style lang="scss"> | |
.CodeMirror { | |
height: auto; | |
font-family: Consolas, Menlo, Monaco, monospace; | |
font-size: 13px; | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment