vue使用highlight.js

发布: 2019-04-01 11:58:06标签: vue

vue使用highlight.js

01<template>
02 <div ref="code" class="code" v-html="html"></div>
03</template>
04
05<script>
06import hljs from 'highlight.js'
07import 'highlight.js/styles/androidstudio.css'
08
09export default {
10 props: {
11 html: {
12 type: String,
13 default: ''
14 }
15 },
16 watch: {
17 html() {
18 this.$nextTick(() => {
19 this.init()
20 })
21 }
22 },
23 mounted() {
24 this.init()
25 },
26 methods: {
27 init() {
28 const codes = this.$refs.code.querySelectorAll('pre code');
29 // 不使用ol样式太丑了
30 codes.forEach((block, num) => {
31 hljs.highlightBlock(block)
32 let i = 1
33 const n = (m) => `<em class="line-label">${m > 9 ? m : '0' + m}</em>`
34 block.innerHTML = `<div class="line">${n(i)}${block.innerHTML.replace(/\n/g, function (word) {
35 i += 1
36 return `</div><div class="line">${n(i)}`
37 })}</div>`
38 })
39 }
40 }
41}
42</script>
43
44<style lang="scss">
45.hljs {
46 .line {
47 padding: 0;
48 line-height: 1.4;
49 .line-label {
50 color: #999;
51 height: 100%;
52 padding: 0 0.8rem 0 0.2rem;
53 }
54 }
55}
56</style>
57
复制代码