image with caption - vuepress

3.2k Views Asked by At

I'm trying to create a component in vuepress to display an image with its caption. When I hardcode the image path, the image appears but this way I will not have a reusable component. I already try with props, but it doesn't work either.

Here is how I already tried:

<template>
    <figure>
      <!-- <img src="../../guides/contribute/images/typora-tela1.png" alt=""/> -->
      <img :src="imagesrc" alt=""/>
      <figcaption>Legenda: {{ caption }} - {{ src }}</figcaption>
    </figure>
</template>
<script>
...
props: ['src'],
computed: {
    imagesrc () {
      return '../../guides/contribute/images/' + this.src // this.image
    }
  }
...
</script>

On my README.md I call the component like this: <captioned-image src="filename.png" caption="Caption Example" /> but the image doesn't appear.

How can I fix this issue? Is it possible to do this with markdown only?

2

There are 2 best solutions below

2
On BEST ANSWER

In markdown (without a Vue component) you can use html,

<figure>
  <img src='../../guides/contribute/images/typora-tela1.png'>
  <figcaption>Caption Example</figcaption>
</figure>

To make the CaptionedImage.vue component work I think you need to put the images in the /.vuepress/public/ folder.

The difference (as I understand it) is that within the markdown the image path is handled at compile time, but for the component the image path is resolved at runtime.

Anything placed in /.vuepress/public/ is available at runtime referenced from the page root.

This works for me:

project structure

<project root folder>
  docs
    .vuepress
      components
        CaptionedImage.vue
      public
        images
          myImage.jpg
    ReadMe.md

CaptionedImage.vue

<template>
  <figure>
    <img :src="imagesrc" alt=""/>
    <figcaption>Legenda: {{ caption }} - {{ src }}</figcaption>
  </figure>
</template>
<script>
export default {
  props: ['src', 'caption'],
  computed: {
    imagesrc () {
      return './images/' + this.src
    }
  }
}
</script>

ReadMe.md

<CaptionedImage src="myImage.jpg" caption="Caption Example"></CaptionedImage>
0
On

Thanks to Richard. Based on what he did, I changed a little. So that

  • image shows in the center.
  • width can be changed very easily.
  • caption show in small size and italic font.

Cimg.vue

<template>
  <figure align='center'>
    <img :src="imagesrc" :width="width" alt=""/>
    <figcaption><i><small>{{ caption }}</small></i></figcaption>
  </figure>
</template>

<script>
export default {
  props: ['src', 'caption', 'width'],
  computed: {
    imagesrc () {
      return  this.src
    }
  }
}
</script>

ReadMe.md

For example:

<Cimg src='/images/ml/GAN/永野芽郁.jpg' width='100%' caption="《半分、青い》 玲爱"/>

Here is the final effect.