Vue中通过highlight.js实现代码高亮
2021-02-03 05:17
标签:type org span git bin stat directive 代码 网站 在 新建 在 自定义插件官方文档 自定义指令官方文档 highlightjs官方网站 highlightjs Demo地址 vue-highlightjs Github地址 Vue中通过highlight.js实现代码高亮 标签:type org span git bin stat directive 代码 网站 原文地址:https://www.cnblogs.com/Jimc/p/13161836.html
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);
四、使用插件
pre v-highlight="sourcecode">code>code>pre>
pre v-highlight>code>const s = new Date().toString()code>pre>
参考: