想用codemirror
做实时代码高亮,自定义了双向指令来使用它。定义为全局指令后可正常使用,定义为局部指令则css不正确(也许是js也有问题?)
使用vue-cli
的webpack模版建项目。codemirror
通过npm安装。代码:
main.js
import Vue from 'vue'
import App from './App'
import CodeMirror from 'codemirror/lib/codemirror'
import 'codemirror/lib/codemirror.css'
import 'codemirror/mode/javascript/javascript'
Vue.directive('banzi', {
twoWay: true,
bind: function () {
this.codemirror = CodeMirror(this.el, {
mode: 'javascript',
lineNumbers: true
})
this.codemirror.on('change', function () {
this.set(this.codemirror.getValue())
}.bind(this))
},
update: function (value, oldValue) {
this.codemirror.setValue(value || '')
}
})
/* eslint-disable no-new */
new Vue({
el: 'body',
data: {
'neirong': 'function test() {}'
},
components: { App }
})
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<h1>from app</h1>
<app></app>
<h1>from banzi</h1>
<p v-banzi="neirong"></p>
</html>
components/App.vue
<template>
<!--<textarea id="myTextArea2" cols="10" rows="10" v-snippet="msg" v-model="msg"></textarea>-->
<p id="app" v-snippet="msg"></p>
</template>
<script>
import CodeMirror from 'codemirror/lib/codemirror'
import 'codemirror/lib/codemirror.css'
import 'codemirror/mode/javascript/javascript'
export default {
data () {
return {
msg: ''
}
},
directives: {
'snippet': {
twoWay: true,
bind: function () {
this.editor = CodeMirror(this.vm.$el, {
lineNumbers: true,
mode: 'javascript'
})
this.handler = function () {
this.set(this.editor.getValue(), true)
}.bind(this)
this.editor.on('change', this.handler)
},
update: function (value, oldValue) {
this.editor.setValue(value || '')
console.log(this.editor.getMode())
}
}
}
}
</script>
上面app
那个是来自组件App.vue
的结果,行号显示和代码冲突了,有overlap
看这里吧,有人写了一个: