一,使用
1.下载
npm install highlight.js --save
2.封装成全局自定义指令 utils/highlight.js
import hljs from "highlight.js";
import 'highlight.js/styles/stackoverflow-light.css'
//sql语言提供的关键字不全可以自定义补充
var sql = hljs.getLanguage('sql')
var key = ['use','go','if','while','type','proc']
sql.keywords['keyword'] = sql.keywords['keyword'].concat(key)
hljs.registerLanguage('sql',function(hljs){
return {...sql}
})
//多行注释有问题处理多行注释
function replaceHTML(str){
const regexs = /(<([^>]+)>)/gi;
const tempStr = str.replace(regexs, ''); // 删除所有HTML标签
return `<div class="hljs-comment">${tempStr}</div>`
}
let Highlight = {}
Highlight.install = function (Vue) {
Vue.directive('highlight', {
inserted: function (el, binding) {
},
componentUpdated: function (el, binding) {
let blocks = el.querySelectorAll('pre code')
for (let i = 0; i < blocks.length; i++) {
hljs.highlightBlock(blocks[i])
if(binding.value.type=='noneLight' && binding.value.index.length){
let vals = binding.value.index.findIndex(key=>key==i)
if(vals!=-1){
el.querySelectorAll('pre code')[i].innerHTML = replaceHTML(el.querySelectorAll('pre code')[i].innerHTML)
}
}
}
},
bind (el, binding) {
let blocks = el.querySelectorAll('pre code')
for (let i = 0; i < blocks.length; i++) {
const color = 'background:red;'
hljs.highlightBlock(blocks[i])
if(binding.value.type=='noneLight' && binding.value.index.length){
let vals = binding.value.index.findIndex(key=>key==i)
if(vals!=-1){
el.querySelectorAll('pre code')[i].innerHTML = replaceHTML(el.querySelectorAll('pre code')[i].innerHTML)
}
}
}
}
})
}
export default Highlight;
3.在main.js中引入
// 代码高亮
import Highlight from './utils/hightlight';
Vue.use(Highlight)
4.在页面内使用index.vue
<template>
<div class="code-lines" id="lineId" v-highlight="{type:'noneLight',index:cancleArr}">
<pre style="margin:-20px 0 0 0;">
<code class="code-line-item language-sql" :class="item.myClass" v-for="(item,index) in content" :key="index" >
<div>{{item.code}}</div>
</code>
</pre>
</div>
</template>
<script>
export default {
data(){
return {
cancleArr:[],
content:['use arith','go','/*************','注释1','注释2','****/']
}
},
methods:{
init(){
this.cancleArr = this.getSqlNote(this.content)
},
//处理语句中的注释
getSqlNote(arr){
let startIndex = []
let endIndex = []
let cancleArr = []
arr.forEach((item,index)=>{
//以/*开头但不以*/结尾
if(/^\/\*/.test(item)&& !/\*\/$/.test(item)){
startIndex.push(index)
}
//内容只能为*但是以/结尾
if(/^\*+\/$/.test(item)){
endIndex.push(index)
}
})
if(startIndex.length){
startIndex.forEach((item,index)=>{
let start = startIndex[index]
for (let i = start; i < endIndex[index]+1; i++) {
cancleArr.push(i)
}
// console.log(cons,'')
})
}
return cancleArr
},
}
}
</script>
遇到坑:
1.一些关键词没有
2.多行注释不识别