国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

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

2024-05-06 15:24:11
字體:
來源:轉載
供稿:網友

啊哈,又是來推薦一個 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>            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 塔城市| 霍城县| 手机| 东山县| 萍乡市| 竹溪县| 利辛县| 孟村| 商城县| SHOW| 苗栗县| 凤城市| 安丘市| 隆尧县| 滨海县| 黄冈市| 武安市| 宜兴市| 宿迁市| 泸西县| 潼南县| 弥勒县| 安新县| 集安市| 南充市| 达日县| 常山县| 额济纳旗| 萍乡市| 安国市| 藁城市| 长子县| 财经| 惠来县| 滁州市| 墨脱县| 北川| 花莲市| 旌德县| 清水河县| 浠水县|