Home » vue » Codemirror on vue 3, cannot read property 'on' of undefined

Codemirror on vue 3, cannot read property 'on' of undefined

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m trying to mount Codemirror on vue 3, more specifically using laravel/Inertia. and I want that so for each change in the editor, it updates the value of a variable. but the ‘on’ change event never fires

data(){
   return {
      cm: null
   }
}

mounted() {
        this.cm = CodeMirror.fromTextArea(this.$refs.codemirror, {
            mode: 'sql',
            theme: 'lucario',
        }).setSize("100%",200).on('change',function(){
            console.log('Hello')
        })
    },

The component renders as it should, but i have the following error

Cannot read property 'on' of undefined
Answers:

I would assume from the error message that the setSize function on the CodeMirror instance does not return the instance, so is not chainable

Try breaking onto separate lines, something like:

this.cm = CodeMirror.fromTextArea(this.$refs.codemirror, {
  mode: 'sql',
  theme: 'lucario',
 }):

this.cm.setSize("100%",200);

this.cm.on('change',function(){
  console.log('Hello');    
})