CodeHighlight.vue 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <template>
  2. <div class="code-highlight-wrapper">
  3. <pre><code :class="codeClass" ref="codeRef">{{ code }}</code></pre>
  4. </div>
  5. </template>
  6. <script setup>
  7. import { ref, onMounted, computed } from 'vue'
  8. import hljs from 'highlight.js'
  9. import 'highlight.js/styles/atom-one-dark.css'
  10. // Props
  11. const props = defineProps({
  12. code: {
  13. type: String,
  14. required: true
  15. },
  16. language: {
  17. type: String,
  18. default: ''
  19. }
  20. })
  21. const codeRef = ref(null)
  22. // 计算代码类名
  23. const codeClass = computed(() => {
  24. return props.language ? `language-${props.language}` : ''
  25. })
  26. // 高亮代码
  27. onMounted(() => {
  28. if (codeRef.value) {
  29. if (props.language) {
  30. try {
  31. const result = hljs.highlight(props.code, { language: props.language })
  32. codeRef.value.innerHTML = result.value
  33. } catch {
  34. // 如果指定语言失败,使用自动检测
  35. const result = hljs.highlightAuto(props.code)
  36. codeRef.value.innerHTML = result.value
  37. }
  38. } else {
  39. const result = hljs.highlightAuto(props.code)
  40. codeRef.value.innerHTML = result.value
  41. }
  42. }
  43. })
  44. </script>
  45. <style scoped>
  46. .code-highlight-wrapper {
  47. width: 100%;
  48. overflow-x: auto;
  49. }
  50. pre {
  51. margin: 0;
  52. padding: 1rem;
  53. background: #282c34;
  54. border-radius: 8px;
  55. overflow-x: auto;
  56. }
  57. code {
  58. font-family: 'Fira Code', 'Consolas', 'Monaco', monospace;
  59. font-size: 14px;
  60. line-height: 1.5;
  61. }
  62. </style>