vue-codemirror定位光标位置并在光标处插入信息

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处插入

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3是一种流行的JavaScript框架,用于构建用户界面。它具有响应式数据绑定、组件化开发和虚拟DOM等特性,使得开发者可以更高效地构建交互式的Web应用程序。 要安装vue-codemirror,你可以按照以下步骤进行操作: 1. 首先,确保你已经安装了Vue 3。你可以通过在终端中运行以下命令来检查Vue的版本: ``` vue --version ``` 如果没有安装Vue,你可以通过以下命令全局安装Vue CLI: ``` npm install -g @vue/cli ``` 2. 在你的Vue项目中,使用npm或者yarn安装vue-codemirror。在终端中运行以下命令: ``` npm install vue-codemirror ``` 或者 ``` yarn add vue-codemirror ``` 3. 在你的Vue组件中引入vue-codemirror。在需要使用CodeMirror的组件中,可以通过以下方式引入: ```javascript import VueCodemirror from 'vue-codemirror' import 'codemirror/lib/codemirror.css' // 引入CodeMirror的样式文件 export default { components: { VueCodemirror }, // ... } ``` 4. 在模板中使用vue-codemirror。在需要展示CodeMirror编辑器的地方,可以使用`vue-codemirror`组件,并传入相应的属性和事件理函数: ```html <template> <div> <vue-codemirror v-model="code" :options="codemirrorOptions"></vue-codemirror> </div> </template> <script> export default { data() { return { code: '', codemirrorOptions: { // CodeMirror的配置选项 } } }, // ... } </script> ``` 这样,你就成功安装并使用了vue-codemirror插件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值