vue2中,codemirror编辑器的使用

交互说明 

在编辑器中输入{时,会自动弹出选项弹窗,然后可以选值插入。

代码

父组件

<variable-editorv-model="content":variables="variables"placeholder="请输入模板内容..."@blur="handleBlur"
/>data() {return {content: "这是一个示例 {user.name}",variables: [{id: "user",label: "user",type: "object",children: [{ id: "user.name", label: "name", type: "string" },{ id: "user.age", label: "age", type: "number" },],},{id: "items",label: "items",type: "array<object>",children: [{ id: "items.title", label: "title", type: "string" },{ id: "items.price", label: "price", type: "number" },],},],};},handleBlur(val) {console.log("编辑器内容已更新:", val);
},

子组件 

<template><div class="variable-editor"><div ref="editorRef" class="editor-container"></div><el-popoverv-if="variables && variables.length > 0"ref="popover"placement="left-start":value="popoverOpen":visible-arrow="false"trigger="manual"@after-enter="handleAfterOpen"><divclass="tree-wrap my-variable-popover"tabindex="-1"@keydown="handleKeyDown"@keydown.capture="handleKeyDownCapture"ref="treeRef"><el-tree:data="variables":props="defaultProps"default-expand-all:highlight-current="true":current-node-key="selectedKeys[0]"@current-change="handleCurrentChange"@node-click="handleVariableInsert"ref="tree"node-key="id"><div slot-scope="{ node, data }" class="flex-row-center"><i v-if="getTypeIcon(data)" :class="getTypeIcon(data)"></i><span class="ml-1">{{ node.label }}</span></div></el-tree></div><span slot="reference" ref="anchorRef" class="anchor-point"></span></el-popover></div>
</template><script>
import {EditorView,ViewPlugin,placeholder,Decoration,keymap,
} from "@codemirror/view";
import { EditorState, RangeSetBuilder, StateEffect } from "@codemirror/state";
import { defaultKeymap, insertNewlineAndIndent } from "@codemirror/commands";// 扁平化树结构
const flattenTree = (nodes, result = []) => {for (const node of nodes) {result.push({ key: node.id, title: node.label });if (node.children) {flattenTree(node.children, result);}}return result;
};export default {name: "VariableEditor",props: {value: {type: String,default: "",},variables: {type: Array,default: () => [],},placeholder: {type: String,default: "请输入内容...",},},data() {return {popoverOpen: false,selectedKeys: [],editorView: null,lastCursorPos: null,flattenedTree: [],defaultProps: {children: "children",label: "label",},// 类型图标映射typeIcons: {string: "el-icon-document",number: "el-icon-tickets",boolean: "el-icon-switch-button",object: "el-icon-folder","array<object>": "el-icon-collection",},};},computed: {currentIndex() {return this.flattenedTree.findIndex((node) => node.key === this.selectedKeys[0]);},},mounted() {this.flattenedTree = flattenTree(this.variables);this.initEditor();},beforeDestroy() {if (this.editorView) {this.editorView.destroy();}},watch: {variables: {handler(newVal) {this.flattenedTree = flattenTree(newVal);if (this.editorView) {// 重新配置编辑器以更新插件this.editorView.dispatch({effects: StateEffect.reconfigure.of(this.createExtensions()),});}},deep: true,},value(newVal) {if (this.editorView && newVal !== this.editorView.state.doc.toString()) {this.editorView.dispatch({changes: {from: 0,to: this.editorView.state.doc.length,insert: newVal,},});}},popoverOpen(val) {if (val && this.flattenedTree.length > 0) {this.selectedKeys = [this.flattenedTree[0].key];this.$nextTick(() => {if (this.$refs.tree) {this.$refs.tree.setCurrentKey(this.selectedKeys[0]);}});}},},methods: {getTypeIcon(data) {return this.typeIcons[data.type] || this.typeIcons.string;},initEditor() {if (!this.$refs.editorRef) return;this.editorView = new EditorView({doc: this.value,parent: this.$refs.editorRef,extensions: this.createExtensions(),});// 添加失焦事件this.$refs.editorRef.addEventListener("blur", this.onEditorBlur);},createExtensions() {return [placeholder(this.placeholder || "请输入内容..."),EditorView.editable.of(true),EditorView.lineWrapping,keymap.of([...defaultKeymap,{ key: "Enter", run: insertNewlineAndIndent },]),EditorState.languageData.of(() => {return [{ autocomplete: () => [] }];}),this.createUpdateListener(),this.createVariablePlugin(),this.createInterpolationPlugin(this.variables),];},createUpdateListener() {return EditorView.updateListener.of((update) => {if (update.docChanged) {// const content = update.state.doc.toString();// 不要在每次更改时都触发,而是在失焦时触发}});},createVariablePlugin() {const self = this;return ViewPlugin.fromClass(class {constructor(view) {this.view = view;}update(update) {if (update.docChanged || update.selectionSet) {const pos = update.state.selection.main.head;const doc = update.state.doc.toString();// 只有当光标位置真正变化时才更新if (self.lastCursorPos !== pos) {self.lastCursorPos = pos;// 延迟更新 Popover 位置setTimeout(() => {self.$refs.popover &&self.$refs.popover.$el &&self.$refs.popover.updatePopper();}, 10);}// 1. 正则查找所有的 {xxx}const regex = /\{(.*?)\}/g;let match;let inInterpolation = false;while ((match = regex.exec(doc)) !== null) {const start = match.index;const end = start + match[0].length;if (pos > start && pos < end) {// 光标在插值表达式内inInterpolation = true;setTimeout(() => {const coords = this.view.coordsAtPos(pos);const editorRect = this.view.dom.getBoundingClientRect();if (coords) {self.$refs.anchorRef.style.position = "absolute";self.$refs.anchorRef.style.left = `${coords.left - editorRect.left - 10}px`;self.$refs.anchorRef.style.top = `${coords.top - editorRect.top}px`;self.$refs.anchorRef.dataset.start = start;self.$refs.anchorRef.dataset.end = end;self.popoverOpen = true;}}, 0);break;}}if (!inInterpolation) {// 检测输入 { 的情况const prev = update.state.sliceDoc(pos - 1, pos);if (prev === "{") {setTimeout(() => {const coords = this.view.coordsAtPos(pos);const editorRect = this.view.dom.getBoundingClientRect();if (coords) {self.$refs.anchorRef.style.position = "absolute";self.$refs.anchorRef.style.left = `${coords.left - editorRect.left - 10}px`;self.$refs.anchorRef.style.top = `${coords.top - editorRect.top}px`;self.$refs.anchorRef.dataset.start = pos;self.$refs.anchorRef.dataset.end = pos;self.popoverOpen = true;}}, 0);} else {self.popoverOpen = false;}}}}});},createInterpolationPlugin(variables) {const self = this;return ViewPlugin.fromClass(class {constructor(view) {this.decorations = this.buildDecorations(view);}update(update) {if (update.docChanged || update.viewportChanged) {this.decorations = this.buildDecorations(update.view);}}buildDecorations(view) {const builder = new RangeSetBuilder();const doc = view.state.doc;const text = doc.toString();const regex = /\{(.*?)\}/g;let match;while ((match = regex.exec(text)) !== null) {const [full, expr] = match;const start = match.index;const end = start + full.length;const isValid = self.validatePath(variables, expr.trim());const deco = Decoration.mark({class: isValid? "cm-decoration-interpolation-valid": "cm-decoration-interpolation-invalid",});builder.add(start, end, deco);}return builder.finish();}},{decorations: (v) => v.decorations,});},validatePath(schema, rawPath) {const segments = rawPath.replace(/\[(\d+)\]/g, "[$1]").split(".");// 递归匹配function match(nodes, index) {if (index >= segments.length) return true;const currentKey = segments[index];for (const node of nodes) {const { label: title, type, children } = node;// 匹配数组字段,如 abc[0]if (/\[\d+\]$/.test(currentKey)) {const name = currentKey.replace(/\[\d+\]$/, "");if (title === name && type === "array<object>" && children) {return match(children, index + 1);}}// 匹配普通字段if (title === currentKey) {if ((type === "object" || type === "array<object>") && children) {return match(children, index + 1);}// 如果不是object类型,且已经是最后一个字段return index === segments.length - 1;}}return false;}return match(schema, 0);},handleAfterOpen() {if (this.$refs.treeRef) {this.$refs.treeRef.focus();}},handleCurrentChange(data) {if (data) {this.selectedKeys = [data.id];}},handleVariableInsert(data) {const key = data.id;this.selectedKeys = [key];const view = this.editorView;if (!view) return;const state = view.state;const pos = state.selection.main.head;const doc = state.doc.toString();let insertText = `{${key}}`;let targetFrom = pos;let targetTo = pos;let foundInBraces = false;// 检查光标是否在 {...} 内部const regex = /\{[^}]*\}/g;let match;while ((match = regex.exec(doc)) !== null) {const [full] = match;const start = match.index;const end = start + full.length;if (pos > start && pos < end) {targetFrom = start;targetTo = end;foundInBraces = true;break;}}// 如果不在 {...} 中,但光标前是 `{`,只插入 `${key}}`,不要加多一个 `{`if (!foundInBraces && doc[pos - 1] === "{") {targetFrom = pos;insertText = `${key}}`; // 前面已经有 {,只补后半段}const transaction = state.update({changes: {from: targetFrom,to: targetTo,insert: insertText,},selection: { anchor: targetFrom + insertText.length },});view.dispatch(transaction);view.focus();this.popoverOpen = false;},onEditorBlur(e) {const related = e.relatedTarget;// 如果焦点转移到了 Popover 内部,则不处理 blurif (related && related.closest(".my-variable-popover")) {return;}const view = this.editorView;if (view) {this.$emit("input", view.state.doc.toString());this.$emit("blur");}},handleKeyDownCapture(e) {if (!["ArrowUp", "ArrowDown", "Enter"].includes(e.key)) {e.stopPropagation();}},handleKeyDown(e) {if (!["ArrowUp", "ArrowDown", "Enter"].includes(e.key)) return;if (e.key === "ArrowDown") {let nextKey;if (this.currentIndex < this.flattenedTree.length - 1) {nextKey = this.flattenedTree[this.currentIndex + 1].key;} else {nextKey = this.flattenedTree[0].key;}this.selectedKeys = [nextKey];this.$refs.tree.setCurrentKey(nextKey);} else if (e.key === "ArrowUp") {let prevKey;if (this.currentIndex > 0) {prevKey = this.flattenedTree[this.currentIndex - 1].key;} else {prevKey = this.flattenedTree[this.flattenedTree.length - 1].key;}this.selectedKeys = [prevKey];this.$refs.tree.setCurrentKey(prevKey);} else if (e.key === "Enter" && this.selectedKeys[0]) {// 查找对应的节点数据const findNodeData = (key, nodes) => {for (const node of nodes) {if (node.id === key) return node;if (node.children) {const found = findNodeData(key, node.children);if (found) return found;}}return null;};const nodeData = findNodeData(this.selectedKeys[0], this.variables);if (nodeData) {this.handleVariableInsert(nodeData);}}},},
};
</script><style scoped>
.variable-editor {position: relative;width: 100%;
}.editor-container {width: 100%;border: 1px solid #dcdfe6;border-radius: 4px;min-height: 150px;overflow: hidden;transition: border-color 0.2s, box-shadow 0.2s;
}/* CodeMirror 6 编辑器样式 */
:global(.cm-editor) {height: 150px !important;min-height: 150px !important;overflow-y: auto;
}/* 编辑器获取焦点时的样式 */
:global(.cm-editor.cm-focused) {outline: none;
}/* 使用更具体的选择器确保只有一层边框高亮 */
.editor-container:focus-within {border-color: #409eff !important;
}.anchor-point {position: absolute;z-index: 10;
}.tree-wrap {min-width: 200px;
}.flex-row-center {display: flex;align-items: center;flex-wrap: nowrap;
}.ml-1 {margin-left: 4px;
}/* 添加到全局样式中 */
:global(.cm-decoration-interpolation-valid) {color: #409eff;background-color: rgba(64, 158, 255, 0.1);
}:global(.cm-decoration-interpolation-invalid) {color: #f56c6c;background-color: rgba(245, 108, 108, 0.1);text-decoration: wavy underline #f56c6c;
}
</style>

依赖安装 

npm install @codemirror/state @codemirror/view @codemirror/commands

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.pswp.cn/news/907345.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Kafka自定义分区策略实战避坑指南

文章目录 概要代码示例小结 概要 kafka生产者发送消息默认根据总分区数和设置的key计算哈希取余数&#xff0c;key不变就默认存放在一个分区&#xff0c;没有key则随机数分区&#xff0c;明显默认的是最不好用的&#xff0c;那kafka也提供了一个轮询分区策略&#xff0c;我自己…

WPF 全屏显示实现(无标题栏按钮 + 自定义退出按钮)

WPF 全屏显示实现&#xff08;无标题栏按钮 自定义退出按钮&#xff09; 完整实现代码 MainWindow.xaml <Window x:Class"FullScreenApp.MainWindow"xmlns"http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x"http://schemas…

sqli_labs第二十九/三十/三十一关——hpp注入

一&#xff1a;HTTP参数污染&#xff1a; hpp&#xff08;http parameter pollution)注入中&#xff0c;可以通过在hppt的请求中注入多个同名参数来绕过安全过滤 原理&#xff1a;php默认只取最后一个同名参数 比如在这一关里&#xff0c;可能对第一个id参数进行消毒处理&a…

【STM32】按键控制LED 光敏传感器控制蜂鸣器

&#x1f50e;【博主简介】&#x1f50e; &#x1f3c5;CSDN博客专家 &#x1f3c5;2021年博客之星物联网与嵌入式开发TOP5 &#x1f3c5;2022年博客之星物联网与嵌入式开发TOP4 &#x1f3c5;2021年2022年C站百大博主 &#x1f3c5;华为云开发…

华为OD机试真题——斗地主之顺子(2025B卷:100分)Java/python/JavaScript/C/C++/GO最佳实现

2025 B卷 100分 题型 本专栏内全部题目均提供Java、python、JavaScript、C、C++、GO六种语言的最佳实现方式; 并且每种语言均涵盖详细的问题分析、解题思路、代码实现、代码详解、3个测试用例以及综合分析; 本文收录于专栏:《2025华为OD真题目录+全流程解析+备考攻略+经验分…

Qt找不到windows API报错:error: LNK2019: 无法解析的外部符号 __imp_OpenClipboard

笔者在开发中出现的bug完整报错如下&#xff1a; spcm_ostools_win.obj:-1: error: LNK2019: 无法解析的外部符号 __imp_OpenClipboard&#xff0c;函数 "void __cdecl spcmdrv::vCopyToClipboard(char const *,unsigned __int64)" (?vCopyToClipboardspcmdrvYAXPE…

4.8.4 利用Spark SQL实现分组排行榜

在本次实战中&#xff0c;我们的目标是利用Spark SQL实现分组排行榜&#xff0c;特别是计算每个学生分数最高的前3个成绩。任务的原始数据由一组学生成绩组成&#xff0c;每个学生可能有多个成绩记录。我们首先将这些数据读入Spark DataFrame&#xff0c;然后按学生姓名分组&am…

[PyMySQL]

掌握pymysql对数据库实现增删改查数据库工具类封装,数据库操作应用场景数据库操作应用场景 校验测试数据 : 删除员工 :构造测试数据 : 测试数据使用一次就失效,不能重复使用 : 添加员工(is_delete)测试数据在展开测试前无法确定是否存在 : 查询,修改,删除员工操作步骤:!~~~~~~~…

cs224w课程学习笔记-第12课

cs224w课程学习笔记-第12课 知识图谱问答 前言一、问答类型分类二、路径查询(Path queries)2.1 直观查询方法2.2 TransE 扩展2.3 TransE 能力分析 三、连词查询(conjunctive queries)3.1 Query2box 原理1)、投影2)、交集查询&#xff08;AND 操作)3)、联合查询&#xff08;OR 操…

AI任务相关解决方案2-基于WOA-CNN-BIGRU-Transformer模型解决光纤通信中的非线性问题

文章目录 1. 项目背景与研究意义1.1 光纤通信中的非线性问题1.2 神经网络在光纤非线性补偿中的应用现状 2. 现有模型 CNN-BIGRU-attention 分析2.1 模型架构与工作原理2.2 模型性能评估与局限性 3. 新模型优化方案3.1 WOA算法原理与优势3.2 WOA-CNN-BIGRU-MHA模型构建3.3 WOA-C…

HTTP Accept简介

一、HTTP Accept是什么 HTTP协议是一个客户端和服务器之间进行通信的标准协议&#xff0c;它定义了发送请求和响应的格式。而HTTP Accept是HTTP协议中的一个HTTP头部&#xff0c;用于告诉服务器请求方所期望的响应格式。这些格式可以是媒体类型、字符集、语言等信息。 HTTP A…

39-居住证管理系统(小程序)

技术栈: springBootVueMysqlUni-app 功能点: 群众端 警方端 管理员端 群众端: 1.首页: 轮播图展示、公告信息列表 2.公告栏: 公告查看及评论 3.我的: 联系我们: 可在线咨询管理员问题 实时回复 居住证登记申请 回执单查看 领证信息查看 4.个人中心: 个人信息查看及修改…

鸿蒙OSUniApp 开发的滑动图片墙组件#三方框架 #Uniapp

UniApp 开发的滑动图片墙组件 前言 在移动应用中&#xff0c;图片墙是一种极具视觉冲击力的内容展示方式&#xff0c;广泛应用于相册、商品展示、社交分享等场景。一个优秀的滑动图片墙组件不仅要支持流畅的滑动浏览&#xff0c;还要兼容不同设备的分辨率和性能&#xff0c;尤…

碰一碰系统源码搭建==saas系统

搭建“碰一碰”系统&#xff08;通常指基于NFC或蓝牙的短距离交互功能&#xff09;的源码实现&#xff0c;需结合具体技术栈和功能需求。以下是关键步骤和示例代码&#xff1a; 技术选型 NFC模式&#xff1a;适用于Android/iOS设备的近场通信&#xff0c;需处理NDEF协议。蓝牙…

自动驾驶决策规划框架详解:从理论到实践

欢迎来到《自动驾驶决策规划框架详解:从理论到实践》的第二章。在本章中,我们将深入探讨自动驾驶系统中至关重要的“大脑”——决策规划模块。我们将从基本概念入手,逐步解析主流的决策规划框架,包括经典的路径速度解耦方法、工业界广泛应用的Apollo Planning框架、应对复杂…

服务器定时任务查看和编辑

在 Ubuntu 系统中&#xff0c;查看当前系统中已开启的定时任务主要有以下几种方式&#xff0c;分别针对不同类型的定时任务管理方式&#xff08;如 crontab、systemd timer 等&#xff09;&#xff1a; 查看服务器定时任务 一、查看用户级别的 Crontab 任务 每个用户都可以配…

小白的进阶之路系列之四----人工智能从初步到精通pytorch自定义数据集下

本篇涵盖的内容 在之前的文章中,我们已经讨论了如何获取数据,转换数据以及如何准备自定义数据集,本篇文章将涵盖更加深入的问题,希望通过详细的代码示例,帮助大家了解PyTorch自定义数据集是如何应对各种复杂实际情况中,数据处理的。 更加详细的,我们将讨论下面一些内容…

DeepSeek实战:打造智能数据分析与可视化系统

DeepSeek实战:打造智能数据分析与可视化系统 1. 数据智能时代:DeepSeek数据分析系统入门 在数据驱动的决策时代,智能数据分析系统正成为企业核心竞争力。本节将使用DeepSeek构建一个从数据清洗到可视化分析的全流程智能系统。 1.1 系统核心功能架构 class DataAnalysisS…

力扣100题---字母异位词分组

1.字母异位词分组 给你一个字符串数组&#xff0c;请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。 字母异位词 是由重新排列源单词的所有字母得到的一个新单词。 方法一&#xff1a;字母排序 class Solution {public List<List<String>> groupAnagr…

使用子查询在 SQL Server 中进行数据操作

在 SQL Server 中&#xff0c;子查询&#xff08;Subquery&#xff09;是一种在查询中嵌套另一个查询的技术&#xff0c;可以用来执行复杂的查询、过滤数据或进行数据计算。子查询通常被用在 SELECT、INSERT、UPDATE 或 DELETE 语句中&#xff0c;可以帮助我们高效地解决问题。…