当前位置:首页 > VUE

vue代码框实现

2026-01-18 17:32:53VUE

Vue 代码框实现方法

在 Vue 中实现代码框功能通常需要结合语法高亮库或 UI 组件库。以下是几种常见实现方式:

使用第三方库 Prism.js

安装 Prism.js 及相关依赖:

npm install prismjs

在 Vue 组件中使用:

<template>
  <pre><code class="language-javascript">{{ code }}</code></pre>
</template>

<script>
import Prism from 'prismjs';
import 'prismjs/themes/prism.css';

export default {
  data() {
    return {
      code: 'const message = "Hello World";\nconsole.log(message);'
    }
  },
  mounted() {
    Prism.highlightAll();
  }
}
</script>

使用 highlight.js

安装 highlight.js:

npm install highlight.js

组件实现示例:

<template>
  <div>
    <pre v-highlightjs><code class="javascript">{{ code }}</code></pre>
  </div>
</template>

<script>
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';

export default {
  directives: {
    highlightjs(el) {
      const blocks = el.querySelectorAll('code');
      blocks.forEach(block => {
        hljs.highlightBlock(block);
      });
    }
  },
  data() {
    return {
      code: 'function test() {\n  return "test";\n}'
    }
  }
}
</script>

使用 UI 组件库

Element UI 实现方式:

<template>
  <el-card>
    <pre><code class="language-js">{{ code }}</code></pre>
  </el-card>
</template>

Vuetify 实现方式:

<template>
  <v-card>
    <v-card-text>
      <pre><code>{{ code }}</code></pre>
    </v-card-text>
  </v-card>
</template>

自定义样式实现

纯 CSS 实现基础代码框:

<template>
  <div class="code-container">
    <pre><code>{{ code }}</code></pre>
  </div>
</template>

<style>
.code-container {
  background: #f5f5f5;
  border-radius: 4px;
  padding: 16px;
  overflow-x: auto;
}
.code-container code {
  font-family: 'Courier New', monospace;
  color: #333;
}
</style>

动态代码高亮

对于需要动态更新的代码内容:

<template>
  <div>
    <textarea v-model="rawCode"></textarea>
    <pre><code class="language-js" ref="codeBlock">{{ rawCode }}</code></pre>
  </div>
</template>

<script>
import Prism from 'prismjs';

export default {
  data() {
    return {
      rawCode: ''
    }
  },
  watch: {
    rawCode() {
      this.$nextTick(() => {
        Prism.highlightElement(this.$refs.codeBlock);
      });
    }
  }
}
</script>

每种方法各有优劣,Prism.js 和 highlight.js 提供完善的语法高亮功能,而 UI 组件库则提供更丰富的样式和交互功能。根据项目需求选择合适方案即可。

vue代码框实现

标签: 代码vue
分享给朋友:

相关文章

vue实现添加用户

vue实现添加用户

Vue 实现添加用户功能 数据绑定与表单设计 在 Vue 中实现添加用户功能,首先需要设计一个表单,用于收集用户输入的数据。通过 v-model 实现双向数据绑定,确保表单数据与 Vue 实例中的数据…

vue实现横向导航

vue实现横向导航

vue实现横向导航的方法 使用Flex布局实现横向导航 在Vue中可以通过Flex布局快速实现横向导航。创建一个组件,使用display: flex和flex-direction: row属性使导航项…

vue实现按卡片轮播

vue实现按卡片轮播

实现卡片轮播的基本思路 在Vue中实现卡片轮播可以通过结合v-for指令和动态样式绑定完成。核心是维护一个当前显示卡片的索引,通过CSS过渡效果实现平滑切换。 基础实现步骤 模板部分 使用v-for…

vue实现安全免登录

vue实现安全免登录

Vue 实现安全免登录的方案 免登录功能通常通过持久化认证状态(如 Token)实现,但需兼顾安全性。以下是基于 Vue 的常见实现方案: 基于 Token 的免登录 登录成功后存储 Toke…

vue自己实现下拉导航

vue自己实现下拉导航

实现下拉导航的基本思路 在Vue中实现下拉导航,可以通过结合Vue的响应式数据和事件绑定特性来完成。主要思路是利用v-show或v-if控制下拉菜单的显示与隐藏,并通过鼠标事件或点击事件触发状态变化。…

vue实现活动倒计时

vue实现活动倒计时

实现活动倒计时的基本思路 在Vue中实现活动倒计时通常需要获取当前时间与活动结束时间的差值,并将其转换为天、小时、分钟、秒的格式展示。通过定时器每秒更新显示的时间。 定义倒计时数据 在Vue组件的…