qingshuijun 2023-10-01 13:17 采纳率: 50%
浏览 26
已结题

vue-codemirror如何对指定行 指定位置的 字符进行背景颜色或者字体颜色的修改?

回答问题前请先看我的版本我的代码,这一点非常关键

请给你出代码的截图 这是第二点,直接粘贴AI来的代码 我直接无视,三周了 我尝试过各种Ai

请不要粘贴AI 过来的代码,谢谢! 全是不可用的玩意

放置了两个Codemirror,做JSON数据对比,但是大部分资料都是混乱的,5.0 和 6.0 的使用完全不一致,尝试了降低版本,以及各种各博主的方法,但都是碎片

有没有什么方式方法在上面的版本里可以让指定行的指定字符设置class或者style 修改背景颜色的方式方法

document方法就算了,目前就是想把对比出来的数据不一致的行进行标注

vue-codemirror版本6.1.1

codemirror版本6.0.1

codemirror/view 版本6.21.2

codemirror/state 版本 6.2.1

vue版本 3.3.4

<template>
<Codemirror class="codeviewleft" v-model="codeviewleft" :linters="linter" :heightChanged="true" placeholder="Code goes here..." :style="{ height: '96vh' }" :indent-with-tab="true" :tab-size="2" :extensions="extensions" :styleActiveLine="true" @ready="handleReady" @blur="getValue" />
<Codemirror class="codeviewright" v-model="codeviewright" :linters="linter" :heightChanged="true" placeholder="Code goes here..." :style="{ height: '96vh' }" :indent-with-tab="true" :tab-size="2" :extensions="extensions" :styleActiveLine="true"  @blur="getValue" />
<template>
<script setup>
import { ref,reactive,computed,shallowRef,onMounted } from 'vue'
import { Codemirror } from 'vue-codemirror'
import { json,jsonParseLinter  } from '@codemirror/lang-json'  
import { oneDark } from '@codemirror/theme-one-dark'
import { compare } from 'fast-json-patch'
import { countColumn } from '@codemirror/text';
import{EditorState}from"@codemirror/state"
import { Decoration, EditorView, highlightActiveLine } from "@codemirror/view";
const extensions = computed(() => [json(),oneDark])
const codeviewleft =ref('');
const codeviewright =ref('');
const handleReady = (payload) => {
  console.log('↓')
  console.log(payload)
  view.value = payload.view
  state.value = payload.state
}
  const getCodemirrorStates = () => {
    console.log(view.value)
    const state = view.value.state
    const ranges = state.selection.ranges
    const selected = ranges.reduce((r, range) => r + range.to - range.from, 0)
    const cursor = ranges[0].anchor
    const length = state.doc.length
    const lines = state.doc.lines    
    console.log(state)
    console.log(selected)
    console.log(cursor)
    console.log(length)
    console.log(lines)
}
</script>
<style lang='less' scoped>
.highlighted {
  background-color: #ff0000;
}
</style

已安装包如下

    "@codemirror/lang-json": "^6.0.1",
    "@codemirror/state": "^6.2.1",
    "@codemirror/text": "^0.19.6",
    "@codemirror/theme-one-dark": "^6.1.2",
    "@codemirror/view": "^6.20.2"
    "fast-json-patch": "^3.1.1",
    "vue-codemirror": "^6.1.1",
    "codemirror": "^6.0.1"
  • 写回答

12条回答 默认 最新

  • 专家-赤兔[在线] 2023-10-01 13:20
    关注

    引自强大而免费的微信小程序:皆我百晓生。如有帮助,还望采纳。


    要在vue-codemirror中修改指定行和位置的字符的背景颜色或字体颜色,你可以使用Codemirror的Decoration类来实现。首先,你需要获取到EditorView对象,它可以通过ready事件的回调函数参数获得。然后,你可以使用EditorViewaddDecoration方法来添加Decoration对象,从而修改指定位置的字符的样式。

    以下是示例代码,演示如何在指定行、指定位置设置字符的背景颜色:

    <template>
      <Codemirror ref="codemirror" v-model="code" @ready="handleReady" />
    </template>
    
    <script>
    import { ref } from 'vue';
    import { Codemirror } from 'vue-codemirror';
    import { Decoration, EditorView } from '@codemirror/view';
    
    export default {
      components: {
        Codemirror
      },
      setup() {
        const code = ref('');
    
        const handleReady = (editor) => {
          // 获取EditorView对象
          const view = editor.view;
    
          // 创建Decoration对象,设置指定位置的背景颜色
          const deco = Decoration.mark({
            class: 'highlighted', // 样式类名
            attributes: { style: 'background-color: yellow;' } // 背景颜色
          });
    
          // 添加Decoration对象到指定位置
          const from = { line: 2, ch: 5 }; // 指定行和位置
          const to = { line: 2, ch: 10 };
          view.dispatch({ effects: deco.addToRange(EditorView.editable(view), { from, to }) });
        };
    
        return {
          code,
          handleReady
        };
      }
    };
    </script>
    
    <style>
    .highlighted {
      background-color: yellow;
    }
    </style>
    

    在上面的例子中,将class设置为highlighted,然后在<style>中定义了.highlighted的样式,设置了背景颜色为黄色。你可以根据需要修改样式。

    请注意,你需要在CSS样式中定义.highlighted类名,并设置相应的样式,以便修改指定位置字符的背景颜色。

    希望这可以帮助到你!

    评论
  • 「已注销」 2023-10-01 13:41
    关注

    用codemirror提供的api

    评论
  • a谷雨c 2023-10-01 13:46
    关注

    俺也不会

    评论
  • 小明说Java 2023-10-01 14:44
    关注

    建议去官网看看,api应该有介绍

    评论
  • CSDN-Ada助手 CSDN-AI 官方账号 2023-10-01 16:06
    关注

    【相关推荐】



    • 这篇博客: 教你轻松搞懂vue-codemirror的基本用法:主要实现代码编辑、验证提示、代码格式化中的 1. 需要实现codemirror编辑器功能,主要是json数据的编辑 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
      • codemirror基本的编辑代码功能
      • 插入变量功能
      • codemirror验证功能:主要验证代码格式,语法等,给出相应的提示
      • 代码格式化(由于主要是json数据,所以暂时没引用其他组件,如果需要建议引用
      js-beautify,因为查资料发现codemirror在新的版本中已经去掉autoFormatRange方法)

    大致如下图:
    image.png


    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    评论
  • 杨得江-君临天下wyj 2023-10-01 17:17
    关注
    
    <template>
      <Codemirror ref="codemirror" v-model="code" @ready="handleReady" />
    </template>
    <script>
    import { ref } from 'vue';
    import { Codemirror } from 'vue-codemirror';
    import { Decoration, EditorView } from '@codemirror/view';
    export default {
      components: {
        Codemirror
      },
      setup() {
        const code = ref('');
        const handleReady = (editor) => {
          // 获取EditorView对象
          const view = editor.view;
          // 创建Decoration对象,设置指定位置的背景颜色
          const deco = Decoration.mark({
            class: 'highlighted', // 样式类名
            attributes: { style: 'background-color: yellow;' } // 背景颜色
          });
          // 添加Decoration对象到指定位置
          const from = { line: 2, ch: 5 }; // 指定行和位置
          const to = { line: 2, ch: 10 };
          view.dispatch({ effects: deco.addToRange(EditorView.editable(view), { from, to }) });
        };
        return {
          code,
          handleReady
        };
      }
    };
    </script>
    <style>
    .highlighted {
      background-color: yellow;
    }
    </style>
    
    
    
    评论
  • 数据大魔王 2023-10-01 19:29
    关注

    在使用CodeMirror进行JSON数据对比时,可以使用Decoration来设置指定行的样式。用EditorView的state字段来获取编辑器的状态。然后,使用Decoration类创建一个Decoration对象,设置需要标注的行和样式,最后使用EditorView的decorations字段将Decoration对象添加到编辑器中。

    下面演示如何在两个CodeMirror实例中指定的行上设置样式:

    <template>
      <Codemirror class="codeviewleft" v-model="codeviewleft" :linters="linter" :heightChanged="true" placeholder="Code goes here..." :style="{ height: '96vh' }" :indent-with-tab="true" :tab-size="2" :extensions="extensions" :styleActiveLine="true" @ready="handleReady" @blur="getValue" />
      <Codemirror class="codeviewright" v-model="codeviewright" :linters="linter" :heightChanged="true" placeholder="Code goes here..." :style="{ height: '96vh' }" :indent-with-tab="true" :tab-size="2" :extensions="extensions" :styleActiveLine="true"  @blur="getValue" />
    </template>
    <script setup>
      import { ref, computed } from 'vue'
      import { Codemirror } from 'vue-codemirror'
      import { json, jsonParseLinter } from '@codemirror/lang-json'
      import { oneDark } from '@codemirror/theme-one-dark'
      import { EditorView, Decoration } from '@codemirror/view'
    
      const extensions = computed(() => [json(), oneDark])
      const codeviewleft = ref('')
      const codeviewright = ref('')
    
      let editorViews = []
    
      const handleReady = (payload) => {
        const view = payload.view
        const state = payload.state
        editorViews.push({ view, state })
    
        // 获取差异行的行号(示例中使用第1行和第2行作为差异行)
        const diffLines = [0, 1]
    
        // 遍历所有的EditorView,为差异行添加Decoration
        editorViews.forEach(({ view, state }) => {
          const decorations = diffLines.map((line) => {
            const from = view.state.doc.line(line).start
            const to = view.state.doc.line(line).end
            const className = 'highlighted'
            return Decoration.line({
              from,
              to,
              class: className,
            })
          })
          view.dispatch({
            effects: Decoration.set([...state.facet(EditorView.decorations), ...decorations]),
          })
        })
      }
    
      // ...
    </script>
    <style lang="less" scoped>
    .highlighted {
      background-color: #ff0000;
    }
    </style>
    
    

    上述代码中,我使用了一个数组editorViews来存储每个Codemirror实例的EditorView和EditorState对象。handleReady函数被调用时,会将EditorView和EditorState对象添加到editorViews数组中。

    在设置Decoration时,我指定了两个差异行的行号,然后遍历editorViews数组,在每个EditorView中为差异行添加Decoration。通过Decoration.line方法可以创建一个Decoration对象,并设置指定行的行号、样式(class)等。

    最后,我使用view.dispatch方法将新的Decoration添加到编辑器中。可以使用EditorState的facet(EditorView.decorations)方法获取当前已经设置的Decoration,然后将新的Decoration与旧的合并,最后使用effect(Decoration.set)在EditorState中添加新的Decoration。

    示例中差异行行号是静态设置的,你可以根据实际情况动态获取差异行行号,并将其传递给上述代码中的diffLines变量。

    这样,你就可以通过设置差异行的Decoration来修改背景颜色或者添加指定的样式。在示例中,我设置了.highlighted样式来修改背景颜色为红色。你可以根据需要修改样式或者添加其他自定义样式。

    评论
  • coder_small_bell 2023-10-02 16:10
    关注

    codemirror看一下

    评论
  • bug菌¹ Java领域优质创作者 2023-10-02 17:26
    关注

    该回答引用ChatGPT,希望对题主有所帮助,如有帮助,还望采纳。


    可以通过 Codemirror 的 Decoration 功能实现对指定行指定位置字符的样式修改。

    具体步骤如下:

    1. 在 template 中设置一个 ref,用于获取 Codemirror 的实例:
    <template>
      <Codemirror ref="editor" />
    </template>
    
    1. 在 setup 中获取 Codemirror 实例:
    const editorRef = ref(null)
    onMounted(() => {
      const editor = editorRef.value.editor
    })
    
    1. 使用 Decoration 对象设置指定位置字符的样式:
    import { Decoration, EditorView } from '@codemirror/view'
    
    const deco = () => Decoration.mark({
      class: 'highlighted',
      from: { line: 0, ch: 0 },
      to: { line: 0, ch: 5 }
    })
    
    const editor = state.applyAttrs({
      decorations: Decoration.set([
        deco()
      ])
    })
    

    以上代码会将第一行第 1 到 5 个字符设置为了 .highlighted 样式。可以根据需要设置自己的样式,并且动态地根据数据来设置不同行的样式。

    最后,需要在组件中引入样式表:

    <style>
      .highlighted {
        background-color: yellow;
      }
    </style>
    
    评论
  • 心梓知识 2023-10-03 02:09
    关注

    结合GPT给出回答如下请题主参考
    针对vue-codemirror对指定行、指定位置的字符进行背景色或字体颜色修改的问题,可通过以下步骤实现:

    1. 在vue-codemirror组件中,通过ref获取到codemirror实例。

    2. 使用codemirror实例的setCursor方法,将光标设置到指定行指定位置。

    3. 使用codemirror实例的setOption方法,将指定位置的字符设置为背景色或字体颜色。

    下面是一个示例代码:

    <template>
      <div>
        <codemirror ref="cm" v-model="code" :options="cmOptions"></codemirror>
      </div>
    </template>
    
    <script>
    import { codemirror } from 'vue-codemirror'
    
    export default {
      components: {
        codemirror
      },
      data() {
        return {
          code: '',
          cmOptions: {
            mode: 'text/javascript',
            lineNumbers: true
          }
        }
      },
      mounted() {
        this.$nextTick(() => {
          const cm = this.$refs.cm.codemirror // 获取codemirror实例
          cm.setCursor(2, 4) // 设置光标到第3行第5个字符
          cm.setOption('styleSelectedText', { backgroundColor: 'yellow' }) // 设置背景色
        })
      }
    }
    </script>
    

    在上述示例中,代码使用了vue-codemirror组件,并设置了一个codemirror实例。在mounted钩子函数中,通过refs获取到codemirror实例,并使用setCursor方法将光标设置到指定行、指定位置。然后使用setOption方法将指定位置的字符设置为背景色。需要注意的是,该方法只对选择的文本有效。

    希望这个示例能够帮到你。

    评论
  • 玥轩_521 2023-10-03 12:22
    关注

    援引通义千问:
    在Vue-Codemirror中,你可以使用Codemirror的内置方法来修改指定行和指定位置的字符的颜色。以下是一个示例,它将指定行和指定位置的字符的颜色设置为红色:

    <Codemirror class="codeviewleft" v-model="codeviewleft" :linters="linter" :heightChanged="true" placeholder="Code goes here..." :style="{ height: '96vh' }" :indent-with-tab="true" :tab-size="2" :extensions="extensions" :styleActiveLine="true" @ready="handleReady" @blur="getValue" />
    <Codemirror class="codeviewright" v-model="codeviewright" :linters="linter" :heightChanged="true" placeholder="Code goes here..." :style="{ height: '96vh' }" :indent-with-tab="true" :tab-size="2" :extensions="extensions" :styleActiveLine="true"  @blur="getValue" />
    
    <script>
    import { Codemirror } from 'vue-codemirror'
    import { json,jsonParseLinter  } from '@codemirror/lang-json'  
    import { oneDark } from '@codemirror/theme-one-dark'
    import { compare } from 'fast-json-patch'
    import { countColumn } from '@codemirror/text';
    import{EditorState}from"@codemirror/state"
    import { Decoration, EditorView, highlightActiveLine } from "@codemirror/view";
    
    export default {
      name: 'MyComponent',
      data() {
        return {
          codeviewleft: '',
          codeviewright: ''
        }
      },
      mounted() {
        const codeviewleft = this.$refs.codeviewleft
        const codeviewright = this.$refs.codeviewright
        codeviewleft.on('cursorActivity', () => {
          const state = codeviewleft.state
          const line = state.doc.lineAt(state.selection.head)
          const start = line.from.ch
          const end = line.to.ch
          const text = state.doc.text.slice(start, end)
          if (text === 'key') {
            codeviewleft.addLineClass(line.lineNumber, 'background', 'highlighted')
          } else {
            codeviewleft.removeLineClass(line.lineNumber, 'background', 'highlighted')
          }
        })
        codeviewright.on('cursorActivity', () => {
          const state = codeviewright.state
          const line = state.doc.lineAt(state.selection.head)
          const start = line.from.ch
          const end = line.to.ch
          const text = state.doc.text.slice(start, end)
          if (text === 'key') {
            codeviewright.addLineClass(line.lineNumber, 'background', 'highlighted')
          } else {
            codeviewright.removeLineClass(line.lineNumber, 'background', 'highlighted')
          }
        })
      }
    }
    </script>
    

    在这个示例中,我们首先在mounted生命周期钩子中添加了两个事件监听器,一个用于左侧的Codemirror实例,另一个用于右侧的实例。当用户在任何一行中悬停时,这些监听器都会被触发。
    当事件被触发时,我们首先获取了当前选中的行和选中范围内的字符。然后,我们检查这些字符是否包含字符串"key"。如果包含,我们使用addLineClass方法将该行的背景颜色设置为红色;如果不包含,我们使用removeLineClass方法将该行的背景颜色恢复为默认颜色。

    评论
  • 想你依然心痛 全栈领域新星创作者 2023-10-04 09:34
    关注

    可以使用Codemirror的Decoration来实现对指定行指定位置的字符进行样式修改。

    首先需要在组件内部声明一个decorations数组,用于存储需要添加到编辑器中的Decoration对象。

    然后在需要添加样式的地方,使用Decoration.mark方法创建Decoration对象,并将其添加到decorations数组中。

    最后,在编辑器中使用state.update方法更新decorations数组,这样就可以将Decoration应用到编辑器中了。

    以下是一个简单的示例:

    <template>
      <Codemirror v-model="code" :extensions="[json()]" @beforeChange="handleBeforeChange" @update="handleUpdate" />
    </template>
    
    <script>
    import { ref } from "vue";
    import { json } from "@codemirror/lang-json";
    import { Decoration, EditorState } from "@codemirror/view";
    import { Text } from "@codemirror/state";
    
    export default {
      setup() {
        const code = ref(`{
      "name": "John",
      "age": 30,
      "city": "New York"
    }`);
    
        const decorations = ref([]);
    
        const handleBeforeChange = (instance, changeObj) => {
          decorations.value = [];
    
          const { line, ch } = changeObj.from;
    
          // 在第1行第5个字符处添加红色背景色
          if (line === 0 && ch === 4) {
            decorations.value.push(
              Decoration.mark({
                class: "highlighted",
              }).range(Text.Range(changeObj.from, changeObj.to))
            );
          }
        };
    
        const handleUpdate = (instance, changeObj) => {
          const state = EditorState.create({
            doc: code.value,
            decorations: decorations.value,
          });
    
          instance.update([{
            from: Text.Pos(0),
            to: Text.Pos(code.value.split("\n").length),
            changes: state.changes,
          }]);
        };
    
        return {
          code,
          handleBeforeChange,
          handleUpdate,
        };
      },
    };
    </script>
    
    <style>
    .highlighted {
      background-color: red;
    }
    </style>
    

    在上面的示例中,我们监听了beforeChange事件,以便在编辑器中添加Decoration。在这个示例中,我们在第1行第5个字符处添加了一个红色背景色。在handleUpdate中,我们使用最新的Decoration更新编辑器。在这个示例中,我们将state对象中的Decoration应用到了编辑器中。

    需要注意的是,在使用Decoration时,要确保在使用之前初始化Decorations数组,否则会出现错误。

    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 10月4日
  • 修改了问题 10月4日
  • 修改了问题 10月4日
  • 修改了问题 10月2日
  • 展开全部

悬赏问题

  • ¥80 用PE可以更改原win11系统的环境变量吗?
  • ¥20 win10商店接入问题
  • ¥15 java 这种树形框吗
  • ¥40 找同学帮敲Python代码
  • ¥15 MYSQL 订单的商品明细重复计算问题
  • ¥15 微信实时共享位置修改
  • ¥100 TG的session协议号转成直登号号后客户端登录几分钟后自动退出设备
  • ¥50 共模反馈回路的小信号增益
  • ¥15 arduino ssd1306函数与tone函数放歌代码不兼容问题
  • ¥70 0.96版本hbase的row_key里含有双引号,无法deleteall