Pairing SimpleMDE and Vue.js
SimpleMDE is an embeddable JavaScript based Markdown editor, Vue.js is a progressive JavaScript web framework, a match made in heaven you might think? Well, yes, but it takes a little know-how to get them working together and it’s not quite as simple as you might think.
The problem arrises when trying to get the contents of a SimpleMDE skinned textarea into a Vue.js v-model bound variable, it doesn’t get through with the same ease as with a none Vue.js form - not even if you set the forceSync option of SimpleMDE. The solution is to wrap SimpleMDE in a Vue.js component, like so:
First include SimpleMDE in your Vue.js enabled webpage.
<link rel="stylesheet" href="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.css">
<script src="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.js"></script>
That’s the way I did it, because I had to operate within certain constraints, but you could install it via bower or npm as per the SimpleMDE documentation.
Next you need to add SimpleMDE as a component to your Vue instance.
Vue.component('simplemde', {
props: ['value'],
template: `
<textarea ref="area"></textarea>
`,
mounted() {
this.mde = new SimpleMDE({
element: this.$refs.area, // Tie SimpleMDE to your textarea
// Set your SimpleMDE configuration here
// e.g. remove the status bar (status: false), customise the
// toolbar (toolbar: ["bold", "italic", "heading"]) or similar
})
this.mde.value(this.value)
var self = this
this.mde.codemirror.on('change', function() {
// Catch on change events
self.$emit('input', self.mde.value())
})
},
watch: {
// Setup a watch to track changes,
// and only update when changes are made
value(newVal) {
if (newVal != this.mde.value()) {
this.mde.value(newVal)
}
}
},
beforeDestroy() {
// Clean up when the component gets destroyed
this.mde.toTextArea()
}
})
Then simply use the component as per normal Vue.js components, here mdetext
is a variable in your Vue data
section.
<simplemde
v-model="mdetext">
</simplemde>
And there you have it, SimpleMDE and Vue.js working together in harmony.