You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

如何在json-editor-vue结合vanilla-jsoneditor@3.8.0中追踪光标位置并获取当前编辑的键

如何在json-editor-vue结合vanilla-jsoneditor@3.8.0中追踪光标位置并获取当前编辑的键

刚好我之前做类似需求的时候研究过vanilla-jsoneditor的内部API,虽然官方README没明确提到,但确实有办法实现你的需求,给你梳理两个可行的方案:

方案1:监听选区变化事件(推荐)

vanilla-jsoneditor内部其实提供了onChangeSelection事件,能在光标或选区变化时触发,完全符合你需要“光标移动时收到通知”的需求。步骤如下:

  1. 给vue中的json-editor-vue组件添加ref,方便获取底层编辑器实例:
<json-editor-vue ref="jsonEditor" :value="yourJsonData" />
  1. 在组件的mounted钩子中,获取底层的vanilla-jsoneditor实例,并监听选区变化事件:
mounted() {
  // 获取封装的vanilla-editor实例
  const vanillaEditor = this.$refs.jsonEditor.editor;
  
  // 注册选区变化监听
  vanillaEditor.onChangeSelection((selection) => {
    const currentKey = this.extractCurrentKey(selection);
    if (currentKey) {
      console.log('当前聚焦的键:', currentKey);
      // 这里可以执行你的通知逻辑,比如更新页面状态、触发回调等
    }
  });
}
  1. 实现解析选区获取键的函数:
    选区对象里的anchor.path会记录光标所在位置的完整路径,比如光标在k3的值上时,路径是['k2', 'k3'],取最后一段就是我们要的键;如果光标直接在键k3上,路径的最后一段也会是该键,所以可以直接取路径的最后一个元素:
extractCurrentKey(selection) {
  // 校验选区和路径是否有效
  if (!selection?.anchor?.path) return null;
  
  const pathSegments = selection.anchor.path;
  const lastSegment = pathSegments[pathSegments.length - 1];
  
  // 只返回字符串类型的键(过滤数组的数字索引,如果你需要数组索引可以去掉这个判断)
  return typeof lastSegment === 'string' ? lastSegment : null;
}

方案2:周期性检查光标位置(备选)

如果因为版本兼容问题,onChangeSelection事件无法正常触发,你可以用周期性检查的方案,每隔一段时间主动获取当前选区:

mounted() {
  const vanillaEditor = this.$refs.jsonEditor.editor;
  
  // 每500毫秒检查一次,间隔可以根据需求调整
  this.cursorCheckTimer = setInterval(() => {
    const currentSelection = vanillaEditor.getSelection();
    const currentKey = this.extractCurrentKey(currentSelection);
    
    if (currentKey) {
      console.log('当前聚焦的键:', currentKey);
    }
  }, 500);
}

beforeUnmount() {
  // 组件销毁时记得清除定时器,避免内存泄漏
  if (this.cursorCheckTimer) {
    clearInterval(this.cursorCheckTimer);
  }
}

这里的extractCurrentKey函数和方案1里的完全一致。

一些注意事项

  • 要确认你的json-editor-vue版本确实会暴露底层的editor实例,在对应vanilla-jsoneditor@3.8.0的封装版本里是支持的
  • 如果处理的是数组,路径最后一段是数字类型的索引,你可以根据需求选择返回索引或者忽略
  • 当光标在空白区域或编辑器未聚焦时,可能返回null,记得做边界处理

亲测这两个方案在vanilla-jsoneditor@3.8.0上都能正常工作,你可以根据自己的场景选择合适的方式。

内容来源于stack exchange

火山引擎 最新活动