给它添加行数"/>
vue项目使用highlight.js 代码高亮插件,并给它添加行数
效果图:
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 + 1const lineNumberElement = document.createElement('span')lineNumberElement.className = 'line-number'lineNumberElement.textContent = lineNumberlineNumberContainer.appendChild(lineNumberElement)})// 将伪元素插入代码块前面block.parentNode.insertBefore(lineNumberContainer, block)} else {// 如果不需要显示行号,移除之前添加的行号伪元素const lineNumberContainer = block.previousElementSiblingif (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,}
},
更多推荐
vue项目使用highlight.js 代码高亮插件,并给它添加行数
发布评论