Vue 页面高亮显示代码块
Vue 页面可以基于 vue-prism-editor 实现高亮显示代码块,支持 Vue 2.x 和 Vue 3.x。
·
前言
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 |
更多推荐
已为社区贡献5条内容
所有评论(0)