当前位置:首页 > VUE

vue怎么实现文本代码实现

2026-01-14 01:43:33VUE

Vue 实现文本代码展示的方法

在 Vue 中展示代码文本通常需要结合语法高亮和格式化的功能,以下是几种常见的实现方式:

使用 <pre><code> 标签 通过 HTML 原生标签包裹代码文本,保留原始格式和缩进:

<template>
  <pre><code>{{ codeText }}</code></pre>
</template>
<script>
export default {
  data() {
    return {
      codeText: 'const message = "Hello Vue";\nconsole.log(message);'
    }
  }
}
</script>

结合语法高亮库(如 highlight.js) 安装 highlight.js 并注册为 Vue 全局组件或局部组件:

npm install highlight.js

在 Vue 中注册并使用:

import hljs from 'highlight.js';
import 'highlight.js/styles/github.css'; // 选择样式主题

Vue.directive('highlight', {
  inserted(el) {
    hljs.highlightBlock(el);
  }
});

模板中使用:

<pre v-highlight><code class="javascript">const foo = () => 'bar';</code></pre>

使用第三方 Vue 组件(如 vue-prism-editor) 安装组件库:

npm install vue-prism-editor prismjs

实现示例:

import { PrismEditor } from 'vue-prism-editor';
import 'vue-prism-editor/dist/prismeditor.min.css';

export default {
  components: { PrismEditor },
  data() {
    return {
      code: 'console.log("动态代码")'
    }
  }
}

模板调用:

<prism-editor v-model="code" language="js" line-numbers />

动态代码渲染的注意事项

当需要动态渲染用户输入的代码时,应避免直接使用 v-html 以防止 XSS 攻击。建议通过以下方式处理:

// 使用 DOMPurify 清理危险内容
import DOMPurify from 'dompurify';

const safeCode = DOMPurify.sanitize(userInputCode);

对于需要交互的代码编辑器场景,可集成 Monaco Editor(VS Code 同款引擎):

npm install monaco-editor

封装组件示例:

vue怎么实现文本代码实现

import * as monaco from 'monaco-editor';

export default {
  mounted() {
    this.editor = monaco.editor.create(
      this.$refs.editorContainer,
      {
        value: this.code,
        language: 'javascript'
      }
    );
  }
}

标签: 文本代码
分享给朋友:

相关文章

php实现文件下载代码

php实现文件下载代码

实现文件下载的基本方法 使用PHP实现文件下载的核心是通过设置HTTP头部信息,强制浏览器触发下载行为而非直接显示文件内容。 $file_path = 'path/to/your/file.ext'…

vue简单代码实现

vue简单代码实现

以下是一个基于 Vue 3 的简单代码实现示例,包含基础功能演示: 基础模板结构 <!DOCTYPE html> <html lang="en"> <head>…

vue实现文本插值

vue实现文本插值

文本插值的基本语法 在Vue中,文本插值通过双大括号{{ }}实现,将数据绑定到DOM元素中。例如: <div id="app"> {{ message }} </div>…

vue 实现git代码对比

vue 实现git代码对比

Vue 实现 Git 代码对比 在 Vue 中实现 Git 代码对比功能,可以通过集成现有的代码对比库或调用 Git 相关 API 来实现。以下是几种常见的方法: 使用 diff2html 库 di…

vue 富文本实现原理

vue 富文本实现原理

Vue 富文本实现原理 Vue 中实现富文本编辑通常基于现成的库(如 Quill、TinyMCE)或原生 contenteditable 属性。以下是核心实现原理和技术要点: 基于 contente…

vue实现代码实例

vue实现代码实例

以下是一个基于 Vue 3 的完整代码实例,包含核心功能实现和常见开发场景的示例: 基础组件示例 <template> <div> <h1>{{ ti…