Paulund

VueJS Markdown Editor

Markdown editors for writing are becoming a lot more popular these days, they make writing very easy you don't have to worry and styling you just write. You can quickly create a H1 by simply adding a # before the header. In this tutorial, we're going to create a makrdown editor in VueJS and provide a realtime HTML preview of the text you enter. First we need to install a new package called Marked from NPM which will compile the markdown and compile it into HTML.


npm install marked --save

With the Marked package installed you can use this in your VueJS component by importing it from the node_modules folder.


import marked from 'marked';

In the HTML all you need to do is attach a data property to your textarea by using v-model. Then in the area you want to display the HTML content you can use the v-html with a computed function that will run each time your data item is changed.


<div class="columns">
    <div class="column is-6">
        <textarea v-model="markdown" class="textarea" rows="600"></textarea>
    </div>

    <div class="column is-6" v-html="compiledMarkdown"></div>
</div>

The computed function will need to take the markdown data property and pass this into the marked function, the return of this will be the HTML of the markdown and be displayed on the page in full HTML.


computed: 
{
   compiledMarkdown: function () {
     return marked(this.markdown || '', { sanitize: true })
   }
},