Vue中通過highlight.js實現代碼高亮


在 vue 項目中,通過highlight.js,如何實現頁面中代碼高亮?

一、安裝highlight.js

npm install highlight.js --save 或 yarn add highlight.js

二、封裝成vue插件

新建highlight.js文件

/**
 * 自定義代碼高亮插件
 */
import hljs from 'highlight.js'
import 'highlight.js/styles/vs.css'

const install = function (Vue) {
    Vue.directive('highlight', {
        deep: true,
        bind (el, binding) {
            // on first bind, highlight all targets
            let targets = el.querySelectorAll('code')

            targets.forEach(target => {
                if (typeof binding.value === 'string') {
                    // if a value is directly assigned to the directive, use this
                    // instead of the element content.
                    target.textContent = binding.value
                }
                hljs.highlightBlock(target)
            })
        },
        componentUpdated (el, binding) {
            // after an update, re-fill the content and then highlight
            let targets = el.querySelectorAll('code')

            targets.forEach(target => {
                if (typeof binding.value === 'string') {
                    // if a value is directly assigned to the directive, use this
                    // instead of the element content.
                    target.textContent = binding.value
                    hljs.highlightBlock(target)
                }
            })
        },
    })

}

if (window.Vue) {
    window['highlight'] = highlight
    Vue.use(install) // eslint-disable-line
}

export default install

三、全局引入自定義插件

src/main.js中:

// highlight.js代碼高亮插件
import Highlight from './directive/highlight'; // 這里是你項目highlight.js所在路徑
Vue.use(Highlight);

四、使用插件

<!-- 1.如果你需要高亮的代碼是一個變量值,那么你可以這樣使用它。 其中 sourcecode 為變量。 -->
<pre v-highlight="sourcecode"><code></code></pre>

<!-- 2.如果你需要高亮的代碼固定的源代碼,那么你可以這樣使用它。 -->
<pre v-highlight><code>const s = new Date().toString()</code></pre>

參考

自定義插件官方文檔

自定義指令官方文檔

highlightjs官方網站

highlightjs Demo地址

vue-highlightjs Github地址

 


免責聲明!

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



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