Vuejs中通过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地址

猜你喜欢

转载自www.cnblogs.com/Jimc/p/13161836.html
今日推荐