@@ -9,24 +41,45 @@ import { marked } from 'marked';
import hljs from "highlight.js";
//可以设置加载样式切换主题
-import 'highlight.js/styles/atom-one-dark.css'
+import '@/assets/atom-one-dark.css'
import '@/assets/github-markdown.css'
-import { ref,watch } from 'vue';
+import { ref, watch } from 'vue';
-const outputHtml=ref("")
+const outputHtml = ref("")
const props = defineProps(['code'])
-watch(props,(n,o)=>{
+const codeHandler = (code,language) => {
+ const codeIndex = parseInt(Date.now() + "") + Math.floor(Math.random() * 10000000);
+ // 格式化第一行是右侧language和 “复制” 按钮;
+
+ if (code) {
+ try {
+ // 使用 highlight.js 对代码进行高亮显示
+ const preCode =hljs.highlightAuto(code).value;
+ // 将代码包裹在 textarea 中,由于防止textarea渲染出现问题,这里将 "<" 用 "<" 代替,不影响复制功能
+ let html = `
${preCode}
`;
+
+ return html;
+ //
+ } catch (error) {
+ console.log(error);
+ }
+ }
+
+}
+
+watch(props, (n, o) => {
marked.setOptions({
renderer: new marked.Renderer(),
- highlight: function(code) {
- return hljs.highlightAuto(code).value;
- },
+ highlight: function (code,language) {
+ return codeHandler(code,language);
+ // return hljs.highlightAuto(code).value;
+ },
pedantic: false,
gfm: true,//允许 Git Hub标准的markdown
tables: true,//支持表格
-
+
breaks: true,
sanitize: false,
smartLists: true,
@@ -36,8 +89,8 @@ watch(props,(n,o)=>{
}
);
//需要注意代码块样式
- outputHtml.value = marked(n.code).replace(/
/g, "")
-},{immediate:true,deep:true})
+ outputHtml.value = marked(n.code);
+}, { immediate: true, deep: true })