vue项目页面嵌入代码块vue-prism-editor的实现
#代码知识 发布时间: 2026-01-12
需求:
1. 可输入代码,并且代码语法高亮
2. 支持编辑和不可编辑模式
3. 提交到后端到代码内容为字符串格式
实现
在gitbug上找到vue-prism-editor,可以满足以上需求。
使用
1.安装vue-prism-editor
npm install vue-prism-editor
由于vue-prism-editor需要依赖 prismjs,所以还需要安装prismjs
npm install prismjs
2.在需要使用vue-prism-editor的组件中引入
import { PrismEditor } from "vue-prism-editor";
import "vue-prism-editor/dist/prismeditor.min.css"; // import the styles somewhere
// import highlighting library (you can use any library you want just return html string)
import { highlight, languages } from "prismjs/components/prism-core";
import "prismjs/components/prism-clike";
import "prismjs/components/prism-javascript";
import "prismjs/themes/prism-tomorrow.css"; // import syntax highlighting styles
3.html代码
<prism-editor class="my-editor height-300" v-model="code" :highlight="highlighter" :line-numbers="lineNumbers" ></prism-editor>
code----为需要高亮显示的代码内容
highlighter----定义在methods中的一个方法,用于把code高亮显示
lineNumbers----是否可编辑标识
4.js代码
export default {
components: {
PrismEditor
},
data: () => ({
code: 'console.log("Hello World")',
lineNumbers: true, // true为编辑模式, false只展示不可编辑
}),
methods: {
highlighter(code) {
return highlight(code, languages.js); //returns html
}
}
};
5.css代码
<style lang="scss">
/* required class */
.my-editor {
background: #2d2d2d;
color: #ccc;
font-family: Fira code, Fira Mono, Consolas, Menlo, Courier, monospace;
font-size: 14px;
line-height: 1.5;
padding: 5px;
}
/* optional */
.prism-editor__textarea:focus {
outline: none;
}
/* not required: */
.height-300 {
height: 300px;
}
</style>
注意: css样式必写,不然编辑器没有样式,只是纯白页面展示
“height-300” 是给编辑器设置高度的,高度可自行设置,也可以不设置,这个样式非必需
到这里,功能基本就实现了。
但是在过程中遇到一些问题,这里也一并总结。
问题
1.如果仅安装vue-prism-editor,没有安装prismjs,会报以下错误,npm install prismjs即可
2.如果报错中有提示升级或者安装ajv或者vue2.6.X版本,根据提示安装即可
npm install ajv@^6.9.1 npm install vue@^2.6.11
个人理解,如果ajv和vue版本过低,可能会导致vue-prism-editor依赖的相关东西安装不上,建议升级完ajv和vue之后,再重新安装vue-prism-editor和prismjs.
3.vue与vue-template-compiler版本不一致
卸载低版本vue-template-compiler
npm uninstall vue-template-compiler
然后安装跟vue同样版本的vue-template-compiler
npm install vue-template-compiler@2.6.11代码知识SEO
上一篇 : Springmvc ViewResolver设计实现过程解析
下一篇 : python boto和boto3操作bucket的示例
-
SEO外包最佳选择国内专业的白帽SEO机构,熟知搜索算法,各行业企业站优化策略!
SEO公司
-
可定制SEO优化套餐基于整站优化与品牌搜索展现,定制个性化营销推广方案!
SEO套餐
-
SEO入门教程多年积累SEO实战案例,从新手到专家,从入门到精通,海量的SEO学习资料!
SEO教程
-
SEO项目资源高质量SEO项目资源,稀缺性外链,优质文案代写,老域名提权,云主机相关配置折扣!
SEO资源
-
SEO快速建站快速搭建符合搜索引擎友好的企业网站,协助备案,域名选择,服务器配置等相关服务!
SEO建站
-
快速搜索引擎优化建议没有任何SEO机构,可以承诺搜索引擎排名的具体位置,如果有,那么请您多注意!专业的SEO机构,一般情况下只能确保目标关键词进入到首页或者前几页,如果您有相关问题,欢迎咨询!