转载出处
https://www.cnblogs.com/Jimc/p/13161836.html
1添加依赖
npm install highlight.js --save 或 yarn add highlight.js
2创建高亮样式文件 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.如果你需要高亮的代码固定的源代码,那么你可以这样使用它。 -->
const s = new Date().toString()