CodeMirror6在光标处插入文本的正确方法

import {
    
    EditorView} from "@codemirror/view";
import {
    
    EditorSelection} from "@codemirror/state";

方法1

首先 view对象是 EditorView 类对象,如果你使用原生 codemirror 你会手动创建它,如果你使用 vue-codemirror , @ready会把它传给你。

向指定位置插入文本的方法为:

view.dispatch({
    
    
     changes: {
    
    from, to, insert},
})

为此我们需要知道现在光标的位置,获取方法为

view.state.selection.ranges[0]

坑注意: vue-codemirror的 @ready 会给你一个 state 对象,但是不能用那个,必须用 view 下面的 state (看起来是每次内容变动都会创建一个新的state)

这个方法的参数对象里还可以加 selection 参数,在插入之后选中指定范围的文本(选中占位符之类的操作):

view.dispatch({
    
    
    changes: {
    
    from, to, insert}, 
    selection: EditorSelection.range(anchor, head)
})

方法2

来自官网: https://codemirror.net/examples/change/

  view.dispatch(view.state.replaceSelection(text))

这个就是简单的添加

猜你喜欢

转载自blog.csdn.net/hjg719/article/details/130831057