vue3+highlight.js代码高亮插件使用

先安装

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>

后端返回数据
在这里插入图片描述

页面展示效果
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值