话不多说先上图

vue中实现代码高亮,格式化

前一段时间写过一个关于js实现代码高亮的文章 https://mp.csdn.net/postedit/85159364

先在把他整合到vue中

首先先下载highlight.js文件  npm install highlight.js

在main.js中引入文件

//代码高亮文件引入
import hljs from 'highlight.js'
//样式文件,这里我选的是sublime样式,文件里面还有其他样式可供选择
import 'highlight.js/styles/monokai-sublime.css' 

在main.js中然后自定义指令

Vue.directive('highlight',function (el) {
    let blocks = el.querySelectorAll('pre code');
        blocks.forEach((block)=>{
        hljs.highlightBlock(block)
    })
})

位置如图

vue中实现代码高亮,格式化

最后在组件中使用,同样还是要放在pre标签下的code标签里面

<template>
    <div v-highlight> <!-- 使用指令 -->
        <pre>
            <code class="css"><!-- 声明什么类型的代码 -->
                [CSS]
                {
                    width:'100px'
                }
            </code>
            <code class="javascript">
                [javascript]
                var a = 123;
                var b = document.getElementById('tr')
            </code>
            <code class="html">
                [HTML]
                &lt;div&gt;&lt;/div&gt;<!-- html代码需要转义 -->
            </code>
        </pre>
    </div>
</template>
<script>
export default {
    data(){
        return {

        }
    },
    mounted:function(){

    },
    methods:{

    }
}
</script>

就这么简单,搞定

相关文章:

  • 2021-09-15
  • 2020-04-17
  • 2022-01-04
  • 2021-12-02
  • 2018-07-25
  • 2018-03-07
  • 2021-06-23
  • 2021-11-03
猜你喜欢
  • 2021-11-15
  • 2021-10-20
  • 2021-06-17
  • 2021-05-21
  • 2020-12-21
相关资源
相似解决方案