實現Vue 的 markdown 文檔可以在線運行(vue-markdown-run)


閑暇時間我用Vue框架寫了一個博客,編輯器是用的markdown文本的形式,介紹性+描述完全能滿足我的需求,但是,如果想在線運行我markdown文本中的Vue組件代碼,則無法實現了,

於是我就自己寫了一個組件,可以和普通文本顯示器一樣,顯示文本,也可以執行Vue組件代碼(只要標注vue-run)。

下面是介紹:

 

Github代碼倉庫

https://github.com/zhangKunUs...

 

在線運行

https://zhangkunusergit.githu...

 

我已經把我寫的組件提交到npm中,可以引入並使用了,使用方式如下:

安裝

npm install vue-markdown-run --save

 

用法:

(1)完整引入

// 引入
import MarkdownRun from 'vue-markdown-run';
// 全局注入
Vue.use(MarkdownRun);

(2)按需引入

借助 babel-plugin-component,我們可以只引入需要的組件,以達到減小項目體積的目的。

 

首先,安裝 babel-plugin-component:

npm install babel-plugin-component -save-dev

 

然后,將 .babelrc 修改為:

{
  "plugins": [
    [
      "component",
      {
        "libraryName": "vue-markdown-run",
        "styleLibraryName": "theme"
      }
    ]
  ]
}

 

接下來,如果你只需引入部分組件,寫入以下內容:

import { MarkdownRun } from 'vue-markdown-run';

export default {
  components: {
    MarkdownRun
  }
}

 

組件的用法

 <markdown-run
    :mark="markdownTxt"
    highlight-style-file-name="github"
    :runClass=""
    :runStyle=""
    @error=""
  />

 

參數說明

參數 默認值 說明
:mark 必傳(String) markdown文本字符串(具體要求請看下面的“markdownTxt 寫法要求”)
:scope 非(Object) markdown文本中,引入的組件,如果不想全局引入,可以局部引入,用法請看上面的DEMO
highlight-style-file-name 非(String) 'github' markdown代碼部分樣式文件名,此處是指定引入那種樣式(css)文件 詳細請參考:https://highlightjs.org/stati... 中Styles
:runClass 非(String) Vue運行代碼處的css樣式名稱
:runStyle 非(Object) Vue運行代碼處的行間樣式名稱
@error 非(Function) 當前組件執行失敗的回調函數

markdownTxt 寫法要求

代碼中必須指定哪個組件是需要執行的,在上面寫上vue-run, 否則認為是普通文本,不予執行。
vue-run 放在語言類型后面,需要空格,例如:

```html vue-run
<template>
  <div @click="go">Hello, {{name}}! 你可以點擊試試</div>
</template>

<script>
  export default {
    data() {
      return {
        name: 'Vue'
      }
    },
 methods: {
      go () {
        alert('點擊彈出, 代碼vue已執行');
      }
    }
  }
</script>
<style>
 div{
  background-color: red;
 }
</style>

 

如有問題請聯系

郵箱: 1766597067@qq.com


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM