实现效果:

  1. 可输入代码,并且代码语法高亮
  2. 支持编辑和不可编辑模式
  3. 提交到后端到代码内容为字符串格式
    在这里插入图片描述
    搜了很多资料,大都是复制粘贴,写的都一样,还有错的地方,所以整理出一个稍微比较完善的方便你我

⭐⭐ 实现步骤:⭐⭐

1、安装依赖

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 { highlight, languages } from "prismjs/components/prism-core";
import "prismjs/components/prism-clike";
import "prismjs/components/prism-javascript";
import "prismjs/themes/prism-tomorrow.css"; 
3、html代码

<prism-editor
   class="my-editor height-300"
    v-model="code"
    aria-disabled
    :highlight="highlighter"
    line-numbers
    :readonly="false"
    :tabSize="4"
    ></prism-editor>
4、js
export default {
	 components: {
	 		PrismEditor
	 },
	 data: () => ({
	 		code: ' ',
	 }),
	 methods: {
		 	highlighter(code) {
		 		return highlight(code, languages.js); //returns html
		 	}
	 }
};
5、CSS

默认纯白页面展示

<style lang="scss">
	.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;
	}
	
	.prism-editor__textarea:focus {
	 outline: none;
	}
	
	/* 非必须 */
	.height-300 {
	 	height: 300px;
	}
</style>

完成

⭐⭐ 属性事件⭐⭐

1、属性props

属性type默认值描述
v-model valuestring’ ’编辑器的当前值,即要显示的代码
highlightstring => string-methods中的方法,将接收要突出显示的文本的回调。您需要使用prismjs之类的库返回带有语法高亮显示的HTML字符串
lineNumbersBooleanfalse是否显示行号
readonlyBooleanfalse是否可编辑
tabSizeNumber2按tab键时要插入的字符数。例如,对于4空间缩进,tabSize将为4
autoStyleLineNumbersBooleantrue将行号文本颜色与主题匹配
insertSpacesBooleantrue是否使用空格进行缩进。默认值:true。如果将其设置为false,可能还需要将tabSize设置为1
ignoreTabKeyBooleanfalse编辑器是否应忽略按tab键,以便键盘用户可以通过编辑器进行tab。如果设置为false,用户可以使用Ctrl+Shift+M(Mac)/Ctrl+M手动切换此行为。默认值:false
2、事件events

事件名描述
input代码更改时触发
keydown按键按下时触发
keyup按键抬起触发
click鼠标点击触发
focus鼠标获取焦点触发
blur鼠标失去焦点触发
  • ps:有一点换行没有实现,code代码是字符串型,编辑一下会换行,最初赋值的时候不会识别换行,有解决这个问题的欢迎下边留言告诉我哦,万分感谢!!!
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐