当前位置: 移动技术网 > IT编程>脚本编程>vue.js > Vuejs中使用markdown服务器端渲染的示例

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

2017年12月08日  | 移动技术网IT编程  | 我要评论

陈纳德,海安租房,网游之虚实人生

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

安装

直接使用 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>

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

vuejs服务器端渲染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 这个需求来说,容易集成,优点多多。希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网