需求:

vue项目页面嵌入代码块vue-prism-editor的实现

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即可

vue项目页面嵌入代码块vue-prism-editor的实现

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项目页面嵌入代码块vue-prism-editor的实现

卸载低版本vue-template-compiler

npm uninstall vue-template-compiler

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

npm install vue-template-compiler@2.6.11
标签:
vue项目页面嵌入代码块,vue-prism-editor

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
狼山资源网 Copyright www.pvsay.com

《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线

暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。

艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。

《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。