效果图:
1. 首先封装highlight.js,在main中引入即可使用,'./utils/highlight.js' 是我的目录 改成自己的;
// main中引入语法高亮配置
import Highlight from './utils/highlight'
Vue.use(Highlight)
封装:
import Vue from 'vue'
import hljs from 'highlight.js' // 导入 highlight.js
import 'highlight.js/styles/vs2015.css' // 选择适合您的代码高亮样式
hljs.initHighlightingOnLoad()
function highlightCodeAndShowLineNumbers(el, binding) {
// 获取代码块元素
const blocks = el.querySelectorAll('pre code')
// 循环处理每个代码块
blocks.forEach((block) => {
// 高亮代码块
hljs.highlightElement(block)
// 检查是否需要显示行号
if (binding.value && binding.value.showLineNumbers) {
// 获取代码块内容
const code = block.innerText
// 将代码块内容分割成行
const lines = code.split('\n')
// 创建包含行号的伪元素
const lineNumberContainer = document.createElement('span')
lineNumberContainer.className = 'number-container'
// 循环创建并添加行号
lines.forEach((line, index) => {
const lineNumber = index + 1
const lineNumberElement = document.createElement('span')
lineNumberElement.className = 'line-number'
lineNumberElement.textContent = lineNumber
lineNumberContainer.appendChild(lineNumberElement)
})
// 将伪元素插入代码块前面
block.parentNode.insertBefore(lineNumberContainer, block)
} else {
// 如果不需要显示行号,移除之前添加的行号伪元素
const lineNumberContainer = block.previousElementSibling
if (
lineNumberContainer &&
lineNumberContainer.className === 'number-container'
) {
lineNumberContainer.remove()
}
}
})
}
Vue.directive('highlight', {
inserted(el, binding) {
// 初始化时调用
highlightCodeAndShowLineNumbers(el, binding)
},
update(el, binding) {
// 更新时调用
highlightCodeAndShowLineNumbers(el, binding)
},
})
封装showCode 组件:
<template>
<div v-if="code" v-highlight="info" class="code-container">
<pre><code :class="info.language">{{ code }}</code></pre>
</div>
</template>
<script>
export default {
props: {
codeInfo: {
type: Object,
default: () => {
return {}
},
},
},
data() {
return {
info: {},
}
},
computed: {
code() {
return this.codeInfo.code || ''
},
},
mounted() {
this.info = {
showLineNumbers: false,
language: 'javascript',
code: '',
...this.codeInfo,
}
},
methods: {},
}
</script>
<style lang="scss" scoped>
.code-container {
height: 100%;
width: 100%;
overflow: auto;
pre {
display: flex;
// code.hljs {
// padding: 8px 16px;
// flex: 1;
// span {
// display: inline-block;
// }
// }
code {
padding: 8px 16px;
flex: 1;
span {
display: inline-block;
}
}
}
}
</style>
<style lang="scss">
pre {
font-size: 14px;
line-height: 22px;
.number-container {
display: flex;
flex-direction: column;
padding: 8px;
background-color: $--table-header-background-color;
}
}
</style>
使用:
<ShowCode :code-info="headersInfo"> </ShowCode>
headersInfo() {
return {
language: 'http',
showLineNumbers: true,
code: this.bodyDetail,
}
},