You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 16:18:02