ソースを参照

【优化】AI 抽离代码后,代码复制失效问题

cherishsince 1 年間 前
コミット
cfdceca9f3
2 ファイル変更20 行追加2 行削除
  1. 19 2
      src/components/MarkdownView/index.vue
  2. 1 0
      src/views/ai/chat/Message.vue

+ 19 - 2
src/components/MarkdownView/index.vue

@@ -1,14 +1,19 @@
 
 <template>
-  <div v-html="contentHtml"></div>
+  <div ref="contentRef" v-html="contentHtml"></div>
 </template>
 
 <script setup lang="ts">
+import {useClipboard} from "@vueuse/core";
+
 import {marked} from 'marked'
 import 'highlight.js/styles/vs2015.min.css'
 import hljs from 'highlight.js'
 import {ref} from "vue";
 
+const {copy} = useClipboard() // 初始化 copy 到粘贴板
+const contentRef = ref()
+
 // 代码高亮:https://highlightjs.org/
 // 转换 markdown:marked
 
@@ -17,7 +22,7 @@ const renderer = {
   code(code, language, c) {
     const highlightHtml = hljs.highlight(code, {language: language, ignoreIllegals: true}).value
     const copyHtml = `<div id="copy" data-copy='${code}' style="position: absolute; right: 10px; top: 5px; color: #fff;cursor: pointer;">复制</div>`
-    return `<pre>${copyHtml}<code class="hljs">${highlightHtml}</code></pre>`
+    return `<pre style="position: relative;">${copyHtml}<code class="hljs">${highlightHtml}</code></pre>`
   }
 }
 
@@ -54,6 +59,18 @@ const renderMarkdown = async (content: string) => {
 onMounted(async ()  => {
   // 解析转换 markdown
   await renderMarkdown(props.content as string);
+  //
+  // 添加 copy 监听
+  contentRef.value.addEventListener('click', (e: any) => {
+    console.log(e)
+    if (e.target.id === 'copy') {
+      copy(e.target?.dataset?.copy)
+      ElMessage({
+        message: '复制成功!',
+        type: 'success'
+      })
+    }
+  })
 })
 </script>
 

+ 1 - 0
src/views/ai/chat/Message.vue

@@ -202,6 +202,7 @@ onMounted(async () => {
     }
 
     .left-text-container {
+      position: relative;
       display: flex;
       flex-direction: column;
       overflow-wrap: break-word;