Vue3集成Codemirror调用on方法报Cannot read property 'on' of undefined错误
报错根因
- CodeMirror 的
setSize()方法执行后没有返回编辑器实例本身,不支持链式调用。你将.on('change')直接接在setSize()后面,相当于给undefined绑定事件,自然会抛出Cannot read property 'on' of undefined错误,事件也根本没有成功绑定。
修正方案
将链式调用拆分,先给实例变量赋值,再单独调用配置方法、绑定事件即可:
data(){ return { cm: null // 你要同步的响应式变量可以加在这里,比如 content: '' } } mounted() { // 先初始化编辑器并赋值给实例变量 this.cm = CodeMirror.fromTextArea(this.$refs.codemirror, { mode: 'sql', theme: 'lucario', }) // 单独调用setSize设置尺寸 this.cm.setSize("100%",200) // 绑定change事件,用箭头函数避免this指向问题,方便更新组件内响应式变量 this.cm.on('change',(editor) => { console.log('Hello') // 需要同步变量的话直接取编辑器内容即可 // this.content = editor.getValue() }) },
补充注意事项
- 如果你后续改用Vue3组合式API写法,要注意操作ref实例的时候需要加上
.value - 不要用普通函数作为change事件的回调,否则回调内部的
this指向的是编辑器实例,不是Vue组件实例,无法直接更新组件内的响应式变量
内容的提问来源于stack exchange,提问作者Jarliev Pérez
相关产品推荐
相关产品推荐

