在
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>
參考