vue实现代码插件
Vue 实现代码插件的方法
使用 highlight.js 实现语法高亮
安装 highlight.js 和 vue 的封装库:
npm install highlight.js @highlightjs/vue-plugin
在 Vue 项目中注册插件:
import { createApp } from 'vue'
import App from './App.vue'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css' // 选择主题样式
import { HljsVuePlugin } from '@highlightjs/vue-plugin'
const app = createApp(App)
app.use(HljsVuePlugin)
app.mount('#app')
使用组件:
<template>
<highlightjs language="javascript" :code="code" />
</template>
<script>
export default {
data() {
return {
code: 'const message = "Hello, Vue!"'
}
}
}
</script>
自定义代码编辑器组件
创建一个可编辑的代码块组件:

<template>
<div class="code-editor">
<pre><code :class="`language-${language}`">{{ code }}</code></pre>
<textarea v-model="code" @input="updateCode"></textarea>
</div>
</template>
<script>
export default {
props: {
language: {
type: String,
default: 'javascript'
},
value: {
type: String,
default: ''
}
},
data() {
return {
code: this.value
}
},
methods: {
updateCode() {
this.$emit('input', this.code)
this.highlight()
},
highlight() {
// 使用 highlight.js 或其他库处理高亮
}
}
}
</script>
<style>
.code-editor {
position: relative;
}
.code-editor textarea {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0.7;
}
</style>
使用 Monaco Editor 集成
安装 Monaco Editor:
npm install monaco-editor
创建 Vue 组件封装:
<template>
<div ref="container" class="monaco-editor"></div>
</template>
<script>
import * as monaco from 'monaco-editor'
export default {
props: {
value: String,
language: {
type: String,
default: 'javascript'
},
theme: {
type: String,
default: 'vs-dark'
}
},
mounted() {
this.editor = monaco.editor.create(this.$refs.container, {
value: this.value,
language: this.language,
theme: this.theme,
automaticLayout: true
})
this.editor.onDidChangeModelContent(() => {
this.$emit('input', this.editor.getValue())
})
},
beforeUnmount() {
this.editor.dispose()
}
}
</script>
<style>
.monaco-editor {
height: 400px;
width: 100%;
}
</style>
使用 Prism.js 实现轻量级高亮
安装 Prism.js:

npm install prismjs
创建指令:
import Prism from 'prismjs'
import 'prismjs/themes/prism.css'
export default {
mounted(el, binding) {
const code = el.textContent
const language = binding.value || 'javascript'
el.innerHTML = Prism.highlight(code, Prism.languages[language], language)
}
}
注册指令:
import { createApp } from 'vue'
import App from './App.vue'
import prismDirective from './directives/prism'
const app = createApp(App)
app.directive('prism', prismDirective)
app.mount('#app')
使用指令:
<template>
<pre v-prism="'javascript'"><code>{{ code }}</code></pre>
</template>






