Vue+ts+markdown-it代码高亮复制行号

Vue+ts+markdown-it代码高亮复制行号

通过markdown-it 自定义显示markdown组件,实现代码复制按钮和行号显示

安装

// 安装markdown解析器
yarn add  markdown-it
// 安装代码高亮highlight组件
yarn add highlight.js

.d.ts

// 简单声明module 防止ts引入报错

declare module 'markdown-it'
declare module 'highlight.js'

code代码框复制实现

通过在markdown-ithighlight中处理高亮时在合适的位置插入如下html代码

// 复制按钮html   codeId时<core>标签的id
`<div class="toolbar" onclick='window.copyCode("${codeId}")'><img alt="复制"  src="${src}"/><div>${
        txt ? txt : ''
      }</div></div>`

window下挂载全局方法copyCode

 window.copyCode = function (codeId: string) {

       //复制实现
 }

行号

通过在markdown-ithighlight中处理高亮时在合适的位置插入如下html代码

`<ul class="line-box">${lis}</ul>`

获取行号lis

      var lis = ''
      if (array) {// str 是highlight中源码str.split('\n')分割后集合
        for (var i = 1; i <= array.length; i++) {
          lis += `<li>${i}</li>`
        }
      }

markdown

import { defineComponent, onMounted, ref, watch } from 'vue'
import MarkdownIt from 'markdown-it'
import 'highlight.js/styles/atom-one-dark.css'
import 'highlight.js/lib/common'
import './index.less'
import hljs from 'highlight.js'
export default defineComponent({
  name: 'MarkDownBox',
  props: {
    message: {
      type: String,
      default: ''
    },
    showLine: {
      type: Boolean,
      defalut: true
    }
  },
  emits: ['copyCode'],
  setup(props, { emit, slots }) {
    const mdHtml = ref()

    window.copyCode = function (codeId: string) {
      emit('copyCode', document.getElementById(codeId)?.innerText)
    }

    var md = MarkdownIt({
      highlight: function (str: string, lang: string, langAttrs: any) {
        const hasLang = lang && hljs.getLanguage(lang)
        const codes = str.split('\n')
        const id =  getUUID()
        const toolBox = getCodeToolBox(hasLang, lang,id)
        if (hasLang) {
          try {
            return `<pre>${toolBox}<div class="code-box">
            ${props.showLine != false ? getLineBox(codes) : ''}
            <code id="${id}" class="hljs language-${lang}">${hljs.highlight(lang, str, true).value}</code>
            </div></pre>`
          } catch (__) {}
        }
        return `<pre>${toolBox}<div class="code-box">${
          props.showLine != false ? getLineBox(codes) : ''
        }<code id="${id}" class="hljs">${md.utils.escapeHtml(str)}</code></div></pre>`
      }
    })

    const getLineBox = (array: Array<string>) => {
      var lis = ''
      if (array) {
        for (var i = 1; i <= array.length; i++) {
          lis += `<li>${i}</li>`
        }
      }
      return `<ul class="line-box">${lis}</ul>`
    }

    const getCodeToolBox = (hasLang: boolean, lang: string, codeId: string) => {
      return `<div class="tool-box" >
      ${hasLang ? ` <div class="code-lang">${lang}</div>` : ''}
      ${getCodeTool(`window.copyCode('${codeId}')`, require('@/assets/images/icon_copy.png'), '复制')}
      </div>`
    }

    const getCodeTool = (clickFun: string, src: string, txt: string) => {
      return `<div class="toolbar" οnclick="${clickFun}"><img alt="复制"  src="${src}"/><div>${
        txt ? txt : ''
      }</div></div>`
    }

    watch(
      () => props.message,
      (val) => {
        markdown(val)
      }
    )

    const markdown = (msg: string) => {
      mdHtml.value =  md.render( msg  )
    }

    onMounted(() => {
      markdown(props.message)
    })

    return () => {
      return (
        <div
          v-html={mdHtml.value}
        </div>
      )
    }
  }
})

index.less

pre {
    display: flex;
    flex-direction: column;
    width: 100%;
    margin: 10px 0px;
    border: none;
    border-radius: 6px;
    background-color: rgb(34, 34, 34) !important;
    overflow-x: auto;
    color: #fff;
}

pre code {
    background-color: #292b33 !important;
    padding: 12px;
    width: 100%; 
}

.code-box {
    display: flex;
    width: 100%;
}

.line-box {
    color: #cdcdcd;
    text-align: right;
    padding: 12px 8px !important;
    font-size: 14px;
    font-family: 'Courier New', Courier, monospace;
    border-right: 1px solid #7d7d7d;
}

.tool-box {
    width: 100%;
    padding: 4px 12px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    color: white;
    font-size: 14px;

    .code-lang {
        flex: auto;
    }

    .toolbar {
        display: flex;
        align-items: center;
        padding-left: 4px;

        img {
            width: 18px;
            height: 18px;
            margin-right: 1px;
        }
    }
}
  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3 + TypeScript + Vite 中使用 vue-draggable-next 插件实现按钮在区域内任意移动的功能,你可以按照以下步骤进行操作: 1. 确保你已经安装了 Vue 3、TypeScript 和 Vite,并且已经创建了一个 Vue 3 + TypeScript + Vite 的项目。 2. 在项目根目录下,通过命令行安装 vue-draggable-next: ```bash npm install vue-draggable-next ``` 3. 在你的 Vue 组件中,首先导入所需的库和类型: ```typescript import { defineComponent, ref } from 'vue'; import { draggable } from 'vue-draggable-next'; ``` 4. 创建一个包含按钮的区域容器,并在容器内部使用 `draggable` 组件来包裹按钮。将 `v-model` 指令绑定到按钮的位置属性。 ```typescript export default defineComponent({ components: { draggable }, setup() { const buttonPosition = ref({ x: 0, y: 0 }); return { buttonPosition }; } }); ``` 5. 在模板中使用 `draggable` 组件和按钮。 ```html <template> <div class="container"> <draggable v-model="buttonPosition" :bounds="containerBounds"> <button class="button">移动按钮</button> </draggable> </div> </template> ``` 6. 添加样式,确保容器具有适当的宽度、高度和边界。 ```html <style> .container { position: relative; width: 500px; height: 500px; border: 1px solid #ccc; } .button { position: absolute; left: 0; top: 0; } </style> ``` 通过以上步骤,你就可以在 Vue 3 + TypeScript + Vite 中使用 vue-draggable-next 插件来实现按钮在区域内任意移动的功能。这样,按钮的位置将随着拖动而改变,并受到容器边界的限制。希望对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值