这里是引用
安装依赖
npm install codemirror -sava
npm install element-ui
组件
<template>
<div class="in-coder-panel">
<textarea style="height: 100% !important;" ref="textarea" v-model="code"></textarea>
</div>
</template>
<script>
import _CodeMirror from 'codemirror/lib/codemirror'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/darcula.css'
import 'codemirror/addon/hint/show-hint.css'
import {reactive, defineComponent, toRefs, getCurrentInstance, onMounted, onBeforeUnmount} from 'vue'
import 'codemirror/mode/clike/clike.js'
import 'codemirror/mode/r/r.js'
const codemirrorThemList = []
const requireModules = require.context('codemirror/theme/', false, /\.css$/)
requireModules.keys().forEach(value => {
const newValue = value.replace(/^\.\//, '').replace(/\.css$/, '')
codemirrorThemList.push(newValue)
})
const CodeMirror = window.CodeMirror || _CodeMirror
let coder = null
export default defineComponent({
name: 'codeEditor',
props: {
value: {
type: String,
default: ''
},
heightSize: {
type: Number,
default: 500
},
scene: {
type: String,
default: 'look'
},
eventType: {
type: String,
default: 'blur'
},
theme: {
type: String,
default: 'darcula'
}
},
setup(props, {emit}) {
const {proxy} = getCurrentInstance()
const data = reactive({
code: props.value,
options: {
mode: 'text/x-java',
tabSize: 2,
theme: props.theme,
lineNumbers: true,
readOnly: (props.scene === 'add' || props.scene === 'edit') ? false : 'nocursor'
},
initialize: () => {
coder = CodeMirror.fromTextArea(proxy.$refs.textarea, data.options)
const h = props.heightSize + 'px'
coder.setSize('auto', h)
coder.on(props.eventType, coder => {
emit('update:value', coder.getValue())
})
},
importThemDynamic: () => {
return new Promise(resolve => {
codemirrorThemList.forEach(value => {
if (props.theme === value) {
import(`codemirror/theme/${props.theme}.css`)
resolve()
}
})
})
}
})
onMounted(() => {
data.importThemDynamic().then(() => {
data.initialize()
})
})
onBeforeUnmount(() => {
coder.off(props.eventType)
})
return {
...toRefs(data)
}
}
})
</script>
<style>
.in-coder-panel {
flex-grow: 1;
display: flex;
position: relative;
}
.in-coder-panel .CodeMirror {
flex-grow: 1;
text-align: left !important;
z-index: 1;
}
.in-coder-panel .CodeMirror .CodeMirror-code {
line-height: 20px;
}
</style>
引用组件
<template>
<div style="height: 100%">
<codeEditor v-model:value="code" :scene="type" height-size="200"></codeEditor>
<el-button @click="cli">按钮</el-button>
</div>
</template>
<script>
import codeEditor from "./codeEditor";
export default {
data(){
return{
type:'add',
code:''
}
},
components: {
codeEditor
},
methods:{
cli(){
console.log(this.code)
}
}
}
</script>
|