【问题标题】:NUXT: displaying images using Markdown-it relative to markdown contentNUXT:使用 Markdown-it 相对于 markdown 内容显示图像
【发布时间】:2022-02-04 00:39:21
【问题描述】:

这是 Nuxt 的纯静态实现。我正在使用从 yaml 内容文件(不是 markdown)中读取的 markdown 内容。由于内容在 json 对象中,因此它们使用$md.render(blog.content) 呈现。假设 blog.content 是一个 markdown 字符串。

模板如下:

...
<div v-html="$md.render(blog.content)></div>
...

nuxt.config.js 文件有以下内容:

export default {
  target: static,
  ...
  modules: [
    '@nuxt/content',
    '@nuxtjs/markdownit',
    ...
  ],

  markdownit: {
    runtime: true,
    html: true,
  },
  ...
}

这对常规 md 字符串按预期工作。

我想使用存储在博客页面图像子目录中的图像(不是来自资产或静态目录)。并在markdown字符串中引用它

内容目录的结构是:

content
   blogs
      blog1
         images
            b1i1.png
            b1i2.png
         content.yaml
      blog2
         images
         content.yaml
   ...

markdown 字符串可能是这样的

# Study this Digaram
The following is a diagram

<img src="images/b1i1" alt="diagram"/>

有没有办法将此图像发送给 vue 以将其解析为生成图像的路径?谢谢

【问题讨论】:

    标签: nuxt.js markdown


    【解决方案1】:

    默认情况下,Nuxt 内容会查找存储在“statics”目录下的图像。 如果你想从不同的地方访问图片(IE blogs/slug/images)

    您必须手动“要求”它们或为此使用自定义组件,如下所示

    src/components/VImg.vue

    <template>
      <img :src="imgSrc()" :alt="alt" />
    </template>
    
    <script>
    export default {
      props: {
        src: {
          type: String,
          required: true,
        },
        alt: {
          type: String,
          required: true,
        },
        path: {
          type: String,
          required: true,
        },
      },
      methods: {
        imgSrc() {
          try {
            return require(`~/content${this.path}/images/${this.src}`)
          } catch (error) {
            return null
          }
        },
      },
    }
    </script>
    
    • path prop 是博客文章的目录名,前缀为斜线(例如:/blog1)
    • srcprop 为图片名称(如:b1i1.png)

    然后在您的博客 _id 文件中使用它而不是 &lt;img/&gt; 标记(确保根据您的项目结构更改 require(~/content${this.path}/img/${this.src})

    【讨论】:

    • 感谢@udithishara 的回复。我正在使用类似于您建议的自定义 img 标签。但是,在我的用例中,将 md 文本呈现为 HTML 的是 markdown-it 库。而且它无法识别自定义标签。您能否建议任何其他具有 md 是字符串而不是内容文档的约束的方法。谢谢
    猜你喜欢
    • 1970-01-01
    • 2017-05-31
    • 2021-09-24
    • 2020-08-09
    • 2017-02-08
    • 2017-09-11
    • 2015-05-29
    • 2020-06-18
    • 2022-08-18
    相关资源
    最近更新 更多