javascriptvue.jsvuejs2markdownvue-props

Render Markdown In Vue JS


I did a small blog in Vue JS that renders posts with title and description. I would like to be able to use markdown in the description so I used marked.

It works fine when I hard code a text in a data, but trying to pass my description which itself comes from a props, it doesn't work. See below my code I commented what doesn't work and let an example with hard coded data. Any idea how to fix this? With thanks!

<template>
  <div class="til-list">
    <div v-for="til in tils" :key="til">
      <div class="til">
        <h3>{{ til.title }}</h3>
        <p>{{ til.description }}</p>
        <div v-html="markdownToHtml"></div>
        <!-- <div v-html="markdownToHtml(til.description)"></div> -->
        <span v-for="tag in til.tags" :key="tag"> #{{ tag }} </span>
      </div>
    </div>
  </div>
</template>

<script>
import marked from "marked";

export default {
  props: ["tils"],
  // computed: {
  //   markdownToHtml(description) {
  //     return marked(this.description);
  //   },
  // },
  data() {
    return {
      markdown: "# Hello World",
    };
  },
  computed: {
    markdownToHtml() {
      return marked(this.markdown);
    },
  },
};
</script>

Solution

  • Try with methods instead computed property:

    new Vue({
      el: '#demo',
      //props: ["tils"],
      data() {
        return {
          tils: [{title: 'title 1', description: '<b>text</b>'}, {title: 'title 2', description: '<i>text</i>'}]
        };
      },
      methods: {
        markdownToHtml(description) {
          return marked(description);
        },
      }
    
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <div id="demo">
      <div class="til-list">
        <div v-for="(til, index) in tils" :key="index">
          <div class="til">
            <h3>{{ til.title }}</h3>
            <p>{{ til.description }}</p>
            <div v-html="markdownToHtml(til.description)"></div>
            <!--<span v-for="tag in til.tags" :key="tag"> #{{ tag }} </span>-->
          </div>
        </div>
      </div>
    </div>