| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- <template>
- <div class="code-highlight-wrapper">
- <pre><code :class="codeClass" ref="codeRef">{{ code }}</code></pre>
- </div>
- </template>
- <script setup>
- import { ref, onMounted, computed } from 'vue'
- import hljs from 'highlight.js'
- import 'highlight.js/styles/atom-one-dark.css'
- // Props
- const props = defineProps({
- code: {
- type: String,
- required: true
- },
- language: {
- type: String,
- default: ''
- }
- })
- const codeRef = ref(null)
- // 计算代码类名
- const codeClass = computed(() => {
- return props.language ? `language-${props.language}` : ''
- })
- // 高亮代码
- onMounted(() => {
- if (codeRef.value) {
- if (props.language) {
- try {
- const result = hljs.highlight(props.code, { language: props.language })
- codeRef.value.innerHTML = result.value
- } catch {
- // 如果指定语言失败,使用自动检测
- const result = hljs.highlightAuto(props.code)
- codeRef.value.innerHTML = result.value
- }
- } else {
- const result = hljs.highlightAuto(props.code)
- codeRef.value.innerHTML = result.value
- }
- }
- })
- </script>
- <style scoped>
- .code-highlight-wrapper {
- width: 100%;
- overflow-x: auto;
- }
- pre {
- margin: 0;
- padding: 1rem;
- background: #282c34;
- border-radius: 8px;
- overflow-x: auto;
- }
- code {
- font-family: 'Fira Code', 'Consolas', 'Monaco', monospace;
- font-size: 14px;
- line-height: 1.5;
- }
- </style>
|