当前位置: 首页 > news >正文

Vue3使用Monaco-editor

Monaco-editor,一个vs code 编辑器,需要将其继承到项目。不说闲话了,直接上代码。 

npm地址:https://www.npmjs.com/package/monaco-editor

中文文档:https://aydk.site/editor/

安装:

pnpm add monaco-editor -S
pnpm add vite-plugin-monaco-editor -D

配置: 

vite.config.ts

import { defineConfig} from 'vite'// vs code 编辑器配置
import monacoEditorPlugin from 'vite-plugin-monaco-editor'// https://vitejs.dev/config/
export default ({ mode }) => {return defineConfig({plugins: [monacoEditorPlugin({languageWorkers: ['editorWorkerService', 'typescript', 'json', 'html']})]})
}

封装: 

 首先先封装个hook如下:

@/hooks/useMonacoEditor.hook.ts 

import * as monaco from 'monaco-editor'
import useCommonStore from '@/store/common'
import { ref, nextTick, onBeforeUnmount } from 'vue'export function useMonacoEditor(language: string = 'javascript') {// 编辑器示例let monacoEditor: monaco.editor.IStandaloneCodeEditor | null = null// 目标元素const monacoEditorRef = ref<HTMLElement | null>(null)// 创建实例function createEditor(editorOption: monaco.editor.IStandaloneEditorConstructionOptions = {}) {if(!monacoEditorRef.value) returnmonacoEditor = monaco.editor.create(monacoEditorRef.value, {// 初始模型model: monaco.editor.createModel('', language),// 是否启用预览图minimap: { enabled: true },// 圆角roundedSelection: true,// 主题theme: useCommonStore().mode == 'dark' ? 'vs-dark' : 'vs',// 主键multiCursorModifier: 'ctrlCmd',// 滚动条scrollbar: {verticalScrollbarSize: 8,horizontalScrollbarSize: 8},// 行号lineNumbers: 'on',// tab大小tabSize: 2,//字体大小fontSize: 16,// 控制编辑器在用户键入、粘贴、移动或缩进行时是否应自动调整缩进autoIndent: 'advanced',// 自动布局automaticLayout: true,...editorOption})return monacoEditor}// 格式化async function formatDoc() {await monacoEditor?.getAction('editor.action.formatDocument')?.run()}// 数据更新function updateVal(val: string) {nextTick(() => {if(getOption(monaco.editor.EditorOption.readOnly)) {updateOptions({ readOnly: false })}monacoEditor?.setValue(val)setTimeout(async () => {await formatDoc()}, 10)})}// 配置更新function updateOptions(opt: monaco.editor.IStandaloneEditorConstructionOptions) {monacoEditor?.updateOptions(opt)}// 获取配置function getOption(name: monaco.editor.EditorOption) {return monacoEditor?.getOption(name)}// 获取实例function getEditor() {return monacoEditor}// 页面离开 销毁onBeforeUnmount(() => {if(monacoEditor) {monacoEditor.dispose()}})return {monacoEditorRef,createEditor,getEditor,updateVal,updateOptions,getOption,formatDoc}
}

然后调用上面 useMonacoEditor 封装editor编辑器组件

@/components/MonacoEditor/index.vue 

<template><div ref="monacoEditorRef" :style="monacoEditorStyle"></div>
</template>
<script setup lang="ts">
import { useMonacoEditor } from '@/hooks'
import { onMounted, computed, watch } from 'vue'const props = withDefaults(defineProps<{width?: string | number,height?: string | number,language?: string,editorOption?: Object,modelValue: string
}>(), {width: '100%',height: '100%',language: 'javascript',editorOption: () => ({}),modelValue: ''
})const emits = defineEmits<{(e: 'blue'): void,(e: 'update:modelValue', val: string): void
}>()const monacoEditorStyle = computed(() => {return { width: typeof props.width === 'string' ? props.width : props.width + 'px', height: typeof props.height === 'string' ? props.height : props.height + 'px'}
})const { monacoEditorRef, createEditor, updateVal, updateOptions, getEditor } = useMonacoEditor(props.language)onMounted(() => {const monacoEditor = createEditor(props.editorOption)updateMonacoVal(props.modelValue)monacoEditor?.onDidChangeModelContent(() => {emits('update:modelValue', monacoEditor!.getValue())})monacoEditor?.onDidBlurEditorText(() => {emits('blue')})
})watch(() => props.modelValue, () => {updateMonacoVal(props.modelValue)
})function updateMonacoVal(val: string) {if(val !== getEditor()?.getValue()) {updateVal(val)}
}defineExpose({ updateOptions })
</script>

组件使用: 

<div class="edit-container"><MonacoEditor ref="MonacoEditRef" v-model="editJson" language="json" />
</div>
<script setup lang="ts">
import MonacoEditor from '@/components/MonacoEditor/index.vue'
import { ref } from 'vue'let editJson = ref('')const MonacoEditRef = ref<InstanceType<typeof MonacoEditor>>()//MonacoEditRef.value!.updateOptions({ theme: 'vs' }) 调用子组件方法修改配置
</script>

相关文章:

  • 视频列表:点击某个视频进行播放,其余视频全部暂停(同时只播放一个视频)
  • java实体类全部复制到新类及部分复制到新类
  • 2024最新最全:【Windows10】u盘安装系列教程【附安装包】
  • 【笔记】Arrays.binarySearch()实践,以及需要注意的一些问题点
  • Python画图之HelloKitty
  • overflow溢出属性、定位、前端基础之JavaScript
  • 手写一个uniapp的步骤条组件
  • OSPF高级特性2(特殊区域,聚合)
  • 【Linux基础IO篇】系统文件接口(1)
  • 大厂面试题-TCP协议为什么要设计三次握手?
  • Python selenium驱动下载,模块安装以及基本使用
  • fastadmin笔记,关联查询,下拉框,关联下拉框查询,编辑时下拉框默认值
  • ArcGIS制作土地利用现状图
  • 第5天:基础入门-资产架构amp;端口amp;应用amp;CDNamp;WAFamp;站库分离amp;负载均衡
  • Fabric二进制建链(客户端与节点主机分离)
  • [case10]使用RSQL实现端到端的动态查询
  • [译]如何构建服务器端web组件,为何要构建?
  • 【MySQL经典案例分析】 Waiting for table metadata lock
  • 【每日笔记】【Go学习笔记】2019-01-10 codis proxy处理流程
  • ES6 ...操作符
  • es6--symbol
  • If…else
  • Laravel 实践之路: 数据库迁移与数据填充
  • leetcode-27. Remove Element
  • Linux各目录及每个目录的详细介绍
  • Linux后台研发超实用命令总结
  • NSTimer学习笔记
  • passportjs 源码分析
  • Spark VS Hadoop:两大大数据分析系统深度解读
  • 测试如何在敏捷团队中工作?
  • ------- 计算机网络基础
  • 开发了一款写作软件(OSX,Windows),附带Electron开发指南
  • 跨域
  • 快速构建spring-cloud+sleuth+rabbit+ zipkin+es+kibana+grafana日志跟踪平台
  • 区块链共识机制优缺点对比都是什么
  • 腾讯视频格式如何转换成mp4 将下载的qlv文件转换成mp4的方法
  • 写给高年级小学生看的《Bash 指南》
  • 一个项目push到多个远程Git仓库
  • linux 淘宝开源监控工具tsar
  • #LLM入门|Prompt#3.3_存储_Memory
  • #NOIP 2014# day.1 T2 联合权值
  • (07)Hive——窗口函数详解
  • (14)Hive调优——合并小文件
  • (2015)JS ES6 必知的十个 特性
  • (7)STL算法之交换赋值
  • (Arcgis)Python编程批量将HDF5文件转换为TIFF格式并应用地理转换和投影信息
  • (二)fiber的基本认识
  • (附源码)ssm本科教学合格评估管理系统 毕业设计 180916
  • (紀錄)[ASP.NET MVC][jQuery]-2 純手工打造屬於自己的 jQuery GridView (含完整程式碼下載)...
  • (三)docker:Dockerfile构建容器运行jar包
  • (译)计算距离、方位和更多经纬度之间的点
  • (原創) 如何刪除Windows Live Writer留在本機的文章? (Web) (Windows Live Writer)
  • (转)人的集合论——移山之道
  • (转)重识new
  • .bat批处理(十):从路径字符串中截取盘符、文件名、后缀名等信息