When the server reloads, an error occurs stating 'CodeMirror' is not defined when using CodeMirror with Vuejs/Nuxtjs

I've integrated CodeMirror into one of the textarea elements in my Nuxtjs/Vuejs application. I want to format the textarea to resemble XML.

While the CodeMirror functions correctly at times, I encounter an error when reloading the page:

Test.vue
33:18  error  'CodeMirror' is not defined  no-under

Initially, everything works fine. However, after making changes to any file in the project and allowing the Nuxtjs/Vuejs server to reload for the changes to take effect, I receive the error message

error  'CodeMirror' is not defined 

I'm unsure why the error occurs intermittently despite following all necessary steps including adding the required CDN links as suggested in different answers and articles. I would appreciate it if someone could assist me in resolving this issue.

Here are the steps I followed:

  1. Added the following CDNs to my nuxt-config.js: Scripts:
    script: [
      {
        src:"text/javascript",
        src:"https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.32.0/codemirror.min.js"
      },
      {
        src:"text/javascript",
        src:"https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.32.0/mode/xml/xml.min.js"
      }
    ],

CSS:

{
 rel: "stylesheet",
 href:"https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.1/codemirror.min.css"
}

This is how my Test.vue looks like:

<template>
  <div>
    <div class="row">
      <div class="col-md-5">
        <div class="row">
          <div class="col-md-12">
            <textarea
              id="test"
              v-model="xmlInput"
              class="form-control"
              placeholder="XML Document"
              spellcheck="false"
              data-gramm="false"
              @input="convertToJSON()"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      xmlInput: ''
    }
  },
  methods: {
    convertToJSON () {
      console.log('ONE')
      const cm = CodeMirror.fromTextArea(document.getElementById('test'), {
        mode: 'application/xml',
        lineNumbers: true,
        matchBrackets: true,
        styleActiveLine: true,
        lineWrapping: true,
        tabSize: 2,
        value: 'console.log("Hello, World");'
      })
      cm.setSize(500, 500)
    }
  }
}
</script>

<style scoped>
textarea {
  height: 78vh;
  white-space: nowrap;
  resize: both;
}

::-webkit-input-placeholder {
  color: #f1948a;
  text-align: center;
}
</style>

If anyone could provide assistance with this issue, I would greatly appreciate it. Please let me know where I might be going wrong or if you have any suggestions. Thank you in advance.

Sandbox link for reproducing the issue: https://codesandbox.io/s/boring-water-g14zd?file=/pages/index.vue

Error in Sandbox image: https://i.sstatic.net/tTTEq.png

Answer №1

To ensure it functions correctly, consider the following steps.

  • Firstly, avoid re-initializing the codemirror editor for every input change
    @input="convertToJSON()"
  • You can initialize the editor when the component is mounted.

Snippet of Code

<template>
  <div>
    <div class="row">
      XML Data
      <div class="col-md-5">
        <div class="row">
          <div class="col-md-12">
            <textarea
              id="test"
              v-model="xmlInput"
              class="form-control"
              placeholder="XML Document"
              spellcheck="false"
              data-gramm="false"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
export default {
  data() {
    return {
      xmlInput: "",
    };
  },
  mounted() {
    // https://stackoverflow.com/questions/53981928/using-codemirror-cannot-set-property-modeoption-of-undefined
    const editor = document.getElementById("test");
    editor.value = "";
    /** eslint-next-line */
    const cm = CodeMirror.fromTextArea(editor, {
      mode: "application/xml",
      lineNumbers: true,
      matchBrackets: true,
      styleActiveLine: true,
      lineWrapping: true,
      tabSize: 2,
      value: 'console.log("Hello, World");',
    });

    cm.setSize(500, 500);
  },
};

Experience this in action with the link to the Codesandbox demo - https://codesandbox.io/s/falling-cdn-5o0t6?file=/pages/index.vue

If you prefer using the codemirror npm module, access the functional Codesandbox link here - https://codesandbox.io/s/boring-water-g14zd?file=/pages/index.vue

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Hide all elements in jQuery that do not have a class assigned

I've implemented a straightforward jQuery script that toggles the "active" class on an li element when it is clicked: $('li').click(function() { $(this).toggleClass('active'); }); My goal is to hide all other li elements in t ...

transferring a function from a main component to a nested component using swipeout functionality in react-native

I am attempting to transfer a function from a parent container to a child container within react native. The user is presented with a list of items on the screen, where they can swipe the list to reveal additional options. Child import React from &ap ...

You are unable to assign a string value instead of an object when making multiple selections

Utilizing react-select for autocomplete and option-related field has been quite helpful. However, I have noticed that in a single selection scenario, the code provided below only works when sending the value as a string. Unfortunately, it does not function ...

Using JSON with Google Chart Tools

When referring to this example at , it is noted that the method data.addRows() requires a list of lists. A URI (/data/mydata.json) can be accessed to retrieve the following data: [["Canada", 66], ["Turkey", 10], ["Hungary", 23], ["Italy", 49]] Despite a ...

having difficulty carrying out the commands following the post request, without encountering any error messages

I am having trouble executing some instructions after making a post request using an async function that gets called on a button click. async function createPost() { try { await axios.post("http://localhost:3001/post", { content ...

How to retrieve element from templateUrl in AngularJS controller

I am facing a challenge in populating select(option) element inside a template html file from the controller. Although I have managed to do it successfully, I am unable to set a default value to avoid the initial empty option. Here is a snippet from the t ...

Ways to Personalize Navbar in the Bulma Framework

How can I make the <router link> element in my navbar component full width? I'm also looking for keywords related to achieving this layout. Here is an image of the issue: https://i.sstatic.net/2f2b0BcM.png I want a layout that spans the full ...

The function is invoked numerous times

My issue involves using jQuery to handle the mouseenter and mouseleave events. The problem arises when transitioning from one div to another, causing the events to trigger again. I am looking for a solution to only run these events once per mouse enter and ...

Can the keys of an object be retrieved in a specific order?

Is it possible to retrieve keys from a JSON object in the exact same order they were originally received? The use of Object.keys(company).length currently seems to be functioning, but I am seeking reassurance that this method will consistently deliver acc ...

exploring various dynamic elements using jquery

If you need some help figuring this out, take a look at the JSFiddle here. I've set it up for users to input any data they want in the text box, choose a table from set one, and then click the "submit" button to send it. <div> <Div> < ...

What is the process for exporting/importing a variable in Node.js?

What is the correct way to export/import a variable in Node.js? I attempted to use export and import methods, but I received an error message stating that it should be a module. After changing the type to module in the JSON file, it then told me that requ ...

Navigate to a new route in Vue Router and pass parameters as part of the navigation

I have a component that handles programmatic routing based on external data retrieved in the App.vue component and passed down to child components as props. In the child component, the external data is accessed like this: props: { externalData: Array ...

Prevent the movement of the first column in a table when rearranging rows up or down by utilizing

Feeling a bit stuck here, can't seem to figure out what I've missed. I've managed to move up or down a row in a table, but I need the value of the cell in the first column to remain unchanged. Here's my code: This is my HTML file: &l ...

Unable to view Google Map markers within my XPath elements while using Selenium?

Looking to extract data from a Google Maps applet. The specific page can be found here: You can click on items on the map to view displayed information. While typical Google Maps show marker elements, I cannot see them on the provided link when inspecti ...

Controlling Node.js application with Electron app: initiating and terminating

I'm currently working on the functionality to control the start and stop of another node.js application within my electron app. So far, I've managed to successfully start the node application from bot.js by running npm start to launch the electr ...

Discover the steps for generating this graph using ZingChart

I have been experimenting with ZingChart in an attempt to replicate a chart that has the same look and functionality as this example: https://i.stack.imgur.com/PGNK3.png Despite making numerous adjustments to a bar chart, I have not been able to achieve ...

"Is it possible to rearrange the parent div's position when hovering over a child image with jquery sortable

Can you assist me with a task? I have two text boxes with an equal sign image, and I want the user to be able to move the div only when hovering over the equal sign. This means that the user should be able to drag the div using the equal sign. Can you hel ...

React-Troubleshooting list items and keys: A comprehensive guide to resolving common issues

I'm facing a challenge with generating unique key ID's for my list items. Even though I thought I had a good understanding of how unique keys function, it seems that I am mistaken. In the code snippet below, using key={index} or key={item} is no ...

What is the most effective method for postponing the loading of JavaScript?

Incorporating a bootstrap theme into my project has required me to include several javascript files. The challenge arises when some pages load dynamic content from the server, resulting in the entire HTML not being present when the javascript files are exe ...

Troubleshooting Laravel's echo functionality when it doesn't work with dynamically generated

I am utilizing Pusher, Laravel echo, and Vue.js to create a chat application similar to the one shown in this image. Below is the Vue.js code snippet: var myChat = new Vue({ el: '#myChat', data: { the_chat: '', curre ...