先安装
npm install highlight.js
main.js中引入,并注册自定义指令
.....
import hljs from 'highlight.js'
window.hljs = hljs
import 'highlight.js/styles/atom-one-light.css'
import 'highlight.js/lib/common'
import mitt from 'mitt'
.....
app.directive('highlight', {
mounted(el) {
const blocks = el.querySelectorAll('pre code')
blocks.forEach(block => {
hljs.highlightBlock(block) // 高亮代码块
hljs.lineNumbersBlock(block) // 显示行号
})
}
})
fileDetail.vue页面中
<div class="block">
<div class="title"> 二、查看源码 </div>
<div class="desc source-code">
<div v-highlight>
<pre><code :class="detailData.fileSuffix" style="max-height: 500px; overflow: auto">{{ detailData.fileContent }}</code></pre>
</div>
</div>
</div>
// 高亮并滚动到对应一行代码
const activeRow = line => {
setTimeout(() => {
const codeWrap = document.querySelector('.source-code code')
const allline = document.querySelectorAll('.hljs-ln .hljs-ln-code')
allline[line - 1]?.classList.add('danger-line')
codeWrap.scrollTop = allline[line]?.offsetTop - codeWrap.clientHeight / 2
}, 200)
}
// 获取数据
const getDetail = vulId => {
state.loading = true
mistakAlarmDetail({ funId: route.query.type, vulId })
.then(res => {
state.detailData = res
nextTick(() => {
state.pageKey = Math.random()
mistakDetailRef.value.scrollTop = 0
activeRow(res.realRow)
})
})
.finally(() => {
state.loading = false
})
}
<style>
.hljs-ln {
min-width: 100%;
.danger-line {
background-color: pink;
}
}
</style>
后端返回数据
页面展示效果