Vue.js 中使用 vue-markdown 进行 Markdown 渲染与 SSR 示例
本文介绍如何在 Vue.js 项目中集成 vue-markdown 包以支持 Markdown 格式内容的渲染,特别适用于评论系统等场景。文章提供了安装方法、组件使用示例,并展示了结合 Koa 框架实现服务器端渲染(SSR)的完整代码逻辑,帮助开发者快速落地相关功能。
vue-markdown 插件介绍
这里推荐一个用于 Vue.js 的插件:miaolz123/vue-markdown。该插件主要适用于需要在编辑器或评论系统中支持 Markdown 格式的场景。其优势在于默认支持 emoji 表情,使用体验良好,例如 laravist 新版便采用此插件来渲染评论内容。
安装与基础使用
安装
可通过 npm 直接进行安装:
npm install --save vue-markdown
组件集成示例
使用
使用方法十分简便,可以参考以下代码示例:
import VueMarkdown from 'vue-markdown'
new Vue({
components: {
VueMarkdown
}
})
或者采用更具体的实例,例如创建一个名为 Comment.vue 的组件来专门渲染评论内容。在该组件中,可以明确指定相关配置:
import VueMarkdown from 'vue-markdown';
<template>
<div>
<vue-markdown :source="comment.body"></vue-markdown>
</div>
</template>
export default { // ... other codes
props:['comment'],
data(){
return {
comment : this.comment
}
},
components: {
VueMarkdown
},
// ... other codes
}
在渲染阶段,需要处理以下结构:
<div class="comments">
<div class="comments" v-for="comment in comments">
<comment :comment="comment">
</comment>
</div>
</div>
首先通过 props 传入整个 comment 对象,随后在 Comment.vue 中利用 :source 属性将每个评论的 body 字段内容传递给 vue-markdown 组件。需要注意的是,comment.body 在数据库中存储的是 Markdown 格式的内容。
服务器端渲染配置
Vue.js 服务器端渲染 Markdown 示例
const Koa = require('koa');
const _ = require('koa-route');
const vsr = require('vue-server-renderer');
const fs = require('fs');
const indexjs = require('./component/index.js');
const Vue = require('vue');
const MD = require('markdown-it')
const server = new Koa();
const route = {
index: (ctx, id) => {
// 解析markdown
const md = new MD().render(fs.readFileSync('./markdown/' + id + '.md', 'utf-8'));
// vue插入html代码
const app = new Vue({
data: {
main: md
},
template: `
<div>
<div class="main" v-html="main"></div>
</div>`
});
// 其他变量设置
const context = {
htmlTitle: id
};
// 加载模板html文件
const renderer = vsr.createRenderer({
template: fs.readFileSync('./template/index.template.html', 'utf-8')
});
// 渲染
renderer.renderToString(app, context, (err, html) => {
if (err) {
ctx.response.status = 500;
} else {
ctx.response.body = html;
}
})
}
};
server.use(_.get('/post/:id', route.index));
server.listen(8080);
<!DOCTYPE html>
<html lang="CH-ZN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>{{htmlTitle}}</title>
</head>
<body>
<!--vue-ssr-outlet-->
</body>
</html>
总结
本文介绍的 vue-markdown 在特定应用场景下表现优异,尤其是对于希望评论系统支持 Markdown 的需求而言,该插件易于集成且功能丰富。希望本文内容能对各位的学习有所帮助,同时也欢迎大家继续支持本站。
electron-builder打包与发布Electron应用
2026-11-01 05:18:32
Vue结合el-table实现表格行拖拽排序(基于sortablejs)
2026-11-01 01:30:37
详解如何在Vue中进行表单自定义验证
2026-11-01 01:17:28
UniApp 项目中 vue.config.js 配置指南
2026-11-01 00:21:50
uni-app全局变量的四种实现方式总结
2026-11-01 00:15:49
