实现展示代码块功能组件,使用highlight.js完成高亮显示,clipboard插件完成复制功能,并且提供行数展示。
在这里插入图片描述

  1. 安装 highlight.js clipboard
npm install highlight.js clipboard -S
  1. 安装hljsVuePlugin for Vue.js v2

  2. 完整代码

<template>
  <div class="hljs-code-wrapper">
    <ul v-if="code" class="code-numbering">
      <li v-for="(_, index) in new Array(codeLength)" :key="index">{{ index + 1 }}</li>
    </ul>
    <highlightjs language="yaml" :code="code" />
    <el-tooltip content="复制" class="code-copy">
      <i v-if="code" id="copyBtn" :data-clipboard-text="code" class="ri-file-copy-2-line code-copy" @click="handleCopy" />
    </el-tooltip>
  </div>
</template>
<script>
import Clipboard from 'clipboard'
import hljs from 'highlight.js/lib/core.js'
import javascript from 'highlight.js/lib/languages/javascript'
import hljsVuePlugin from '@highlightjs/vue-plugin'
hljs.registerLanguage('javascript', javascript)
import 'highlight.js/styles/atom-one-dark.css'
export default {
  components: {
    highlightjs: hljsVuePlugin.component
  },
  data() {
    return {
      codeLength: 0,
      code: `function test() {
        console.log(test)
      }`
    }
  },
  mounted() {
    const html = document.querySelector('code.hljs')?.innerHTML
    this.codeLength = html ? html.split('\n').length : 0
  },
  methods: {
    handleCopy() {
      var clipboard = new Clipboard('#copyBtn')
      clipboard.on('success', e => {
        this.$message.success('已成功复制到粘贴板')
        clipboard.destroy()
      })
      clipboard.on('error', e => {
        this.$message.warning('该浏览器不支持复制')
        clipboard.destroy()
      })
    }
  }
}
</script>
<style lang='scss'>
.hljs-code-wrapper {
  position: relative;
  code.hljs {
    padding: 1em 1em 1em 4em
  }
  .code-numbering {
    position: absolute;
    top: 1em;
    left: 1em;
    color: #d1d8e6;
    font-size: 14px;
    list-style: none;
    border-right: 1px solid #d1d8e6;
    margin-right: 1em;
    padding-right: 1em;
  }
  i.code-copy {
    position: absolute;
    right: 1em;
    top: 1em;
    display: none;
    cursor: pointer;
    font-size: 18px;
    color: #fff;
    z-index: 999;
  }
  &:hover {
    i.code-copy {
      display: block;
    }
  }
}

</style>
Logo

前往低代码交流专区

更多推荐