vue-codemirror定位光标位置并在光标处插入信息
vue-codemirror定位光标位置并在光标处插入信息业务场景:在代码编辑器外点击按钮,向代码编辑器内的光标处新增一条拼接好的信息。ps:查了好几天如何定位光标都不行,简直要把我搞死了orz直接贴代码<!-- 获取codeMirror中的代码 this.$refs.myCode.codemirror.getValue() --><codemirror ref="myCode"
vue-codemirror定位光标位置并在光标处插入信息
业务场景:在代码编辑器外点击按钮,向代码编辑器内的光标处新增一条拼接好的信息。
代码
<template>
<!-- 获取codeMirror中的代码 this.$refs.myCode.codemirror.getValue() -->
<codemirror ref="myCode" :value="curCode" :options="cmOptions" ></codemirror>
<template>
<script>
function(val) {
let pos1 = this.$refs.myCode.codemirror.getCursor();
let pos2 = {};
pos2.line = pos1.line;
pos2.ch = pos1.ch;
this.$refs.myCode.codemirror.replaceRange(val,pos2);
}
<script>
getCursor方法:
官方文档:
doc.getCursor(?start: string) → {line, ch}
Retrieve one end of the primary selection. start is an optional string indicating which end of the selection to return. It may be “from”, “to”, “head” (the side of the selection that moves when you press shift+arrow), or “anchor” (the fixed side of the selection). Omitting the argument is the same as passing “head”. A {line, ch} object will be returned.
粗暴翻译:
能获取到光标所在的位置,返回一个{line, ch}对象
replaceRange方法:
官方文档:
doc.replaceRange(replacement: string, from: {line, ch}, to: {line, ch}, ?origin: string)
Replace the part of the document between from and to with the given string. from and to must be {line, ch} objects. to can be left off to simply insert the string at position from. When origin is given, it will be passed on to “change” events, and its first letter will be used to determine whether this change can be merged with previous history events, in the way described for selection origins.
粗暴翻译:
用字符串来替代from ~ to之间的文档部分,也可以省略to,直接在from处插入
更多推荐
所有评论(0)