vue使用highlight.js

vue使用highlight.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<template>
<div ref="code" class="code" v-html="html"></div>
</template>

<script>
import hljs from 'highlight.js'
import 'highlight.js/styles/androidstudio.css'

export default {
props: {
html: {
type: String,
default: ''
}
},
watch: {
html() {
this.$nextTick(() => {
this.init()
})
}
},
mounted() {
this.init()
},
methods: {
init() {
const codes = this.$refs.code.querySelectorAll('pre code');
// 不使用ol样式太丑了
codes.forEach((block, num) => {
hljs.highlightBlock(block)
let i = 1
const n = (m) => `<em class="line-label">${m > 9 ? m : '0' + m}</em>`
block.innerHTML = `<div class="line">${n(i)}${block.innerHTML.replace(/\n/g, function (word) {
i += 1
return `</div><div class="line">${n(i)}`
})}</div>`
})
}
}
}
</script>

<style lang="scss">
.hljs {
.line {
padding: 0;
line-height: 1.4;
.line-label {
color: #999;
height: 100%;
padding: 0 0.8rem 0 0.2rem;
}
}
}
</style>