ADDING IMAGES TO MARKDOWN WITH NUXT CONTENT MODULE

Adding Images To Markdown With Nuxt Content Module

Ever wondered how to add images to a Nuxt Content blog post? well it turns out to be pretty simple. All you need to do is create a global image component that we can render inside the markdown posts.

1. Create a dynamic image component

Let's create a new component that's going to be used for our dynamic image. In components we create a new file VImg.vue with the following contents.

<template>
  <picture class="image">
    <img
      :src="imgSrc"
      :alt="alt"
      draggable="false"
    >
  </picture>
</template>

<script>
export default {
  name: 'VImg',
  props: {
    src: {
      type: String,
      required: true
    },
    alt: {
      type: String,
      required: true
    }
  },
  computed: {
    imgSrc () {
      return require(`~/assets/blog/${this.src}`)
    }
  }
}
</script>

<style lang="scss" scoped>
picture {
  width: 100%;
  height: 100%;
  margin: auto;
  display: flex;
  img {
    width: 100%;
    height: 100%;
    margin: auto;
    object-fit: contain;
    padding-bottom: 1rem;
  }
}
</style>

2. Create a global vue plugin

We register the new component by creating a plugin.

In the plugins folder we create a new vimg.js file

import Vue from 'vue'
import VImg from '@/components/global/VImg.vue'

Vue.component('VImg', VImg)

Make sure you add the plugin to your nuxt.config.js

 plugins: [
    '@/plugins/vimg.js'
  ],

Now we should be able to reference the images inside the markdown files with Nuxt Content like this.

<v-img src="image.png" alt="image alt text"></v-img>

Make sure you close the tag correctly or it won't render.

FREELANCE DEVELOPER FOR HIRE

LOOKING FOR A WEB DEVELOPER?