vue中使用highlight.js 高亮代碼塊

項目環(huán)境

近期在做舊項目的重構(gòu),在搭建新項目的時候使用了Vue+Typescript,在前期的準(zhǔn)備工作時,想做一套針對于公司的ui組件庫,element-ui很好,但是個人喜歡花里胡哨。希望用戶能操作的元素上增添些動畫效果。故而自己開始設(shè)計些常有的效果組件。所有使用到了highlight.js這個插件。

一、安裝Highlight.js依賴項

npm install --save highlight.js

二、自定義Vue.js指令:v-highlightjs

在Vue.js組件中使用highlight.js,我們將創(chuàng)建一個名為highlightjs的自定義Vue.js指令。在main.ts文件中直接聲明此指令:

// 代碼高亮插件
import hljs from 'highlight.js';
// 必須導(dǎo)入 否則沒樣式
import 'highlight.js/styles/atom-one-dark-reasonable.css';
const high: any = {
  deep: true,
  bind: function (el: any, binding: any) {
    const targets = el.querySelectorAll('code')
    targets.forEach((target: any) => {
      if (binding.value) {
        target.textContent = binding.value;
      }
      (hljs as any).highlightBlock(target);
    })
  },
  componentUpdated: function (el: any, binding: any) {
    const targets = el.querySelectorAll('code')
    targets.forEach((target: any) => {
      if (binding.value) {
        target.textContent = binding.value;
        (hljs as any).highlightBlock(target);
      }
    })
  }
}
Vue.directive('highlightjs', high)

三、使用v-highlight.js

<pre v-highlightjs><code class="javascript">{{ sourcecode }}</code></pre>
<pre v-highlightjs="sourcecode"><code class="javascript"></code></pre>

四、選擇樣式

highlightjs官網(wǎng)
選擇想要的styles,然后在main.ts的導(dǎo)入樣式文件給替換成對應(yīng)的右側(cè)文件即可

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 基于Vue的一些資料 內(nèi)容 UI組件 開發(fā)框架 實用庫 服務(wù)端 輔助工具 應(yīng)用實例 Demo示例 element★...
    嘗了又嘗閱讀 1,297評論 0 1
  • UI組件 element- 餓了么出品的Vue2的web UI工具套件 Vux- 基于Vue和WeUI的組件庫 m...
    流觴小菜鳥閱讀 1,991評論 2 8
  • UI組件 element- 餓了么出品的Vue2的web UI工具套件 Vux- 基于Vue和WeUI的組件庫 m...
    小姜先森o0O閱讀 10,135評論 0 72
  • UI組件 element- 餓了么出品的Vue2的web UI工具套件 Vux- 基于Vue和WeUI的組件庫 m...
    隨行者pgl閱讀 3,547評論 0 15
  • UI組件 element- 餓了么出品的Vue2的web UI工具套件 Vux- 基于Vue和WeUI的組件庫 m...
    柴東啊閱讀 15,965評論 2 140

友情鏈接更多精彩內(nèi)容