Search code examples
javascriptvuejs3fetch-apivitejavascript-marked

Load file as string in vue/vite project


I have a vue/vie project in which I'm trying to read a markdown file I have into html using marked.

I attempted to use the fetch api to import it as a string, but only because I couldn't figure out how to use node.js code in vue.

Here's the vue file:

<script setup>
import { marked } from 'marked'
</script>

<script>
export default {
    data() {
        return {
            query: this.getQueryVariable("q"),
            markdown: ''
        }
    },
    mounted() {
        fetch('../src/markdown/About.md')
            .then(response => response.text())
            .then(text => this.markdown = text)
        document.querySelector('.marked').innerHTML = marked.parse(this.markdown)
    }
}
</script>

<template>
    <div class='marked'>
    </div>
</template>

Solution

  • You need to update the DOM inside the Promise callback, although doing this via Vue may be preferable:

    fetch("../src/markdown/About.md")
      .then((response) => response.text())
      .then((text) => {
        this.markdown = text;
        document.querySelector(".marked").innerHTML = marked.parse(this.markdown);
      });