makdownit渲染echarts图表

426 阅读1分钟

markdown插件使用的是markdownit我这里使用的是dify,后台返回的数据格式是

```echarts

{

"title": {

"text": "项目人天统计",

"left": "center"

},

"tooltip": {

"trigger": "axis",

"axisPointer": {

"type": "shadow"

        }
......其他配置
    }
}

在renderMarkdown处理的时候进行转换

const renderMarkdown = (content: string, index: number) => {
  if (!md.value) return "";
  content = content.replaceAll("-\ \\", "\\");
  content = content.replaceAll("\\[", "$$");
  content = content.replaceAll("\\]", "$$");
  content = content.replaceAll("\\( ", "$");
  content = content.replaceAll(" \\)", "$");
  content = content.replaceAll("$ ", "$");
  content = content.replaceAll(" $", "$");

  // 替换 echarts 代码块为唯一的 id
  content = content.replace(/```echarts([\s\S]*?)```/g, (match, p1) => {
    const option = JSON.parse(p1);
    eChartOptions.value[index] = option;
    return `<div id="echarts-id-${index}" class="charts_style"></div>`;
  });

  return md.value.render(content);
};

主要是这里的处理,把相关配置项提取出来存入配置项容器中

onMounted(() => {
  md.value = new MarkdownIt({
    html: true,
    breaks: true,
    linkify: true,
    typographer: true
  });
  md.value.use(markdownItKatex);

  nextTick(() => {
    // 渲染所有 ECharts 图表
    eChartOptions.value.forEach((option, index) => {
      const chartDom = document.getElementById(`echarts-id-${index}`);
      if (chartDom) {
        const myChart = echarts.init(chartDom);
        myChart.setOption(option);
      }
    });
  });
});

这里要注意容器的id不能相同采取不同的方法解决