Vue 页面高亮显示代码块

前言

Vue 页面可以基于 vue-prism-editor 实现高亮显示代码块,支持 Vue 2.x 和 Vue 3.x。

提示

  • vue-prism-editor 要求 Vue 的版本高于 2.6.11
  • 若 Vue 的版本为 3.x,则需要使用 vue-prism-editor 的 feature/next 分支代码

安装模块

1
$ npm install vue-prism-editor --save

由于 vue-prism-editor 依赖了 prismjs,所以还需要安装 prismjs

1
$ npm install prismjs --save

Vue 代码

在 Vue 页面中引入 vue-prism-editor 组件,完整的示例代码如下:

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
<template>
  <prism-editor class="my-editor height-300" v-model="code" :highlight="highlighter" readonly line-numbers></prism-editor>
</template>

<script>
  // import Prism Editor
  import { PrismEditor } from 'vue-prism-editor'
  import 'vue-prism-editor/dist/prismeditor.min.css'

  // import highlighting library
  import { highlight, languages } from 'prismjs/components/prism-core'
  import 'prismjs/components/prism-clike'
  import 'prismjs/components/prism-javascript'
  import 'prismjs/themes/prism-tomorrow.css'

  export default {
    components: {
      PrismEditor
    },
    data: () => ({
      code: 'console.log("Hello World")'
    }),
    methods: {
      highlighter (code) {
        return highlight(code, languages.js)
      }
    }
  }
</script>

<style>
  /* required class */
  .my-editor {
    /* we dont use `language-` classes anymore so thats why we need to add background and text color manually */
    background: #2d2d2d;
    color: #ccc;

    /* you must provide font-family font-size line-height. Example: */
    font-family: Fira code, Fira Mono, Consolas, Menlo, Courier, monospace;
    font-size: 14px;
    line-height: 1.5;
    padding: 5px;
  }

  /* optional class for removing the outline */
  .prism-editor__textarea:focus {
    outline: none;
  }

  /* not required: */
  .height-300 {
    height: 300px;
  }
</style>

提示

  • highlighter:定义在 methods 中的一个方法,用于将代码高亮显示
  • readonly:代码块是否只读(不可编辑)
  • code:需要高亮显示的代码内容
  • lineNumbers:是否显示行号

演示效果

常见问题

问题一

如果安装 NPM 模块失败,且错误信息中有提示升级 vue@^2.6.11 版本,则根据提示升级 Vue 的版本即可:

1
$ npm install vue@^2.6.11

问题二

vue 与 vue-template-compiler 的版本不一致,导致 Vue 项目编译失败

首先卸载低版本的 vue-template-compiler

1
$ npm uninstall vue-template-compiler

然后安装跟 vue 相同版本的 vue-template-compiler

1
$ npm install vue-template-compiler@2.6.11
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值