当前位置:Gxlcms > JavaScript > Vuejs中使用markdown服务器端渲染的示例

Vuejs中使用markdown服务器端渲染的示例

时间:2021-07-01 10:21:17 帮助过:4人阅读

啊哈,又是来推荐一个 vuejs 的 package,miaolz123/vue-markdown。 对应的应用场景是:你想使用一个编辑器或者是在评论系统中支持 markdown。这个 package 的有点还是挺多了,比如默认就支持 emoji,这个就很完美啦!laravist 的新版就使用了 vue-markdown 来渲染评论。

安装

直接使用 npm 来安装:

  1. npm install --save vue-markdown

使用

也是很简单的,可以直接这样:

  1. import VueMarkdown from 'vue-markdown'
  2. new Vue({
  3. components: {
  4. VueMarkdown
  5. }
  6. })

或者是这样,举一个具象化的例子是:比如我们有一个 Comment.vue 组件用来渲染评论,可以在这个组件中直接指明:

  1. import VueMarkdown from 'vue-markdown';
  2. <template>
  3. <div>
  4. <vue-markdown :source="comment.body"></vue-markdown>
  5. </div>
  6. </template>
  7. export default { // ... other codes
  8. props:['comment'],
  9. data(){
  10. return {
  11. comment : this.comment
  12. }
  13. },
  14. components: {
  15. VueMarkdown
  16. },
  17. // ... other codes
  18. }

然后在渲染的时候这个:

  1. <div class="comments">
  2. <div class="comments" v-for="comment in comments">
  3. <comment :comment="comment">
  4. </comment>
  5. </div>
  6. </div>

这里我们首先通过 comment props 传入整个 comment(这个comment其实就是一个对象) ,然后在 Comment.vue 通过 :source 来给 veu-markdown 组件传入每个评论的 body 字段内容,注意这里的 comment.body 在数据库中保存的就是评论的 markdown 格式的内容。

Vuejs服务器端渲染markdown示例

  1. const Koa = require('koa');
  2. const _ = require('koa-route');
  3. const vsr = require('vue-server-renderer');
  4. const fs = require('fs');
  5. const indexjs = require('./component/index.js');
  6. const Vue = require('vue');
  7. const MD = require('markdown-it')
  8. const server = new Koa();
  9. const route = {
  10. index: (ctx, id) => {
  11. // 解析markdown
  12. const md = new MD().render(fs.readFileSync('./markdown/' + id + '.md', 'utf-8'));
  13. // vue插入html代码
  14. const app = new Vue({
  15. data: {
  16. main: md
  17. },
  18. template: `
  19. <div>
  20. <div class="main" v-html="main"></div>
  21. </div>`
  22. });
  23. // 其他变量设置
  24. const context = {
  25. htmlTitle: id
  26. };
  27. // 加载模板html文件
  28. const renderer = vsr.createRenderer({
  29. template: fs.readFileSync('./template/index.template.html', 'utf-8')
  30. });
  31. // 渲染
  32. renderer.renderToString(app, context, (err, html) => {
  33. if (err) {
  34. ctx.response.status = 500;
  35. } else {
  36. ctx.response.body = html;
  37. }
  38. })
  39. }
  40. };
  41. server.use(_.get('/post/:id', route.index));
  42. server.listen(8080);
  1. <!DOCTYPE html>
  2. <html lang="CH-ZN">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>{{htmlTitle}}</title>
  8. </head>
  9. <body>
  10. <!--vue-ssr-outlet-->
  11. </body>
  12. </html>

总结

本文介绍的 vue-markdown 在某些应用场景中其实超级好用,特别是对于评论系统想支持 markdown 这个需求来说,容易集成,优点多多。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

人气教程排行