代码示例
本页面展示了VuePress中各种代码展示和高亮的方式,包括语法高亮、行号显示、代码组等功能。
基础代码块
JavaScript代码
// 基础JavaScript示例
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
// 使用示例
console.log(fibonacci(10)); // 输出: 55
// ES6箭头函数版本
const fibonacciArrow = (n) => {
return n <= 1 ? n : fibonacciArrow(n - 1) + fibonacciArrow(n - 2);
};
Vue组件代码
<template>
<div class="hello-world">
<h1>{{ message }}</h1>
<button @click="updateMessage">点击更新</button>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data() {
return {
message: 'Hello Vue!',
items: [
{ id: 1, name: '项目1' },
{ id: 2, name: '项目2' },
{ id: 3, name: '项目3' }
]
}
},
methods: {
updateMessage() {
this.message = `更新时间: ${new Date().toLocaleTimeString()}`
}
},
mounted() {
console.log('组件已挂载')
}
}
</script>
<style scoped>
.hello-world {
padding: 20px;
text-align: center;
}
.hello-world h1 {
color: #42b983;
}
.hello-world button {
background-color: #42b983;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
}
</style>
CSS样式代码
/* 现代CSS Grid布局 */
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
padding: 20px;
}
.grid-item {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 8px;
padding: 20px;
color: white;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease;
}
.grid-item:hover {
transform: translateY(-5px);
}
/* CSS变量使用 */
:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
--border-radius: 8px;
}
.button {
background-color: var(--primary-color);
border-radius: var(--border-radius);
transition: all 0.3s ease;
}
带行号的代码
// 高亮第1行和第3-5行
function quickSort(arr) {
if (arr.length <= 1) {
return arr;
}
const pivot = arr[Math.floor(arr.length / 2)];
const left = [];
const right = [];
const equal = [];
for (let element of arr) {
if (element < pivot) {
left.push(element);
} else if (element > pivot) {
right.push(element);
} else {
equal.push(element);
}
}
return [...quickSort(left), ...equal, ...quickSort(right)];
}
交互式代码演示
实时代码编辑器
JavaScript 在线编辑器
输出结果:
点击"运行代码"查看结果
代码组
多语言示例
::: code-group
// JavaScript 实现
class Calculator {
constructor() {
this.result = 0;
}
add(value) {
this.result += value;
return this;
}
subtract(value) {
this.result -= value;
return this;
}
multiply(value) {
this.result *= value;
return this;
}
divide(value) {
if (value !== 0) {
this.result /= value;
}
return this;
}
getResult() {
return this.result;
}
}
// 使用示例
const calc = new Calculator();
const result = calc.add(10).multiply(2).subtract(5).getResult();
console.log(result); // 15
# Python 实现
class Calculator:
def __init__(self):
self.result = 0
def add(self, value):
self.result += value
return self
def subtract(self, value):
self.result -= value
return self
def multiply(self, value):
self.result *= value
return self
def divide(self, value):
if value != 0:
self.result /= value
return self
def get_result(self):
return self.result
# 使用示例
calc = Calculator()
result = calc.add(10).multiply(2).subtract(5).get_result()
print(result) # 15.0
// Java 实现
public class Calculator {
private double result;
public Calculator() {
this.result = 0;
}
public Calculator add(double value) {
this.result += value;
return this;
}
public Calculator subtract(double value) {
this.result -= value;
return this;
}
public Calculator multiply(double value) {
this.result *= value;
return this;
}
public Calculator divide(double value) {
if (value != 0) {
this.result /= value;
}
return this;
}
public double getResult() {
return this.result;
}
// 使用示例
public static void main(String[] args) {
Calculator calc = new Calculator();
double result = calc.add(10).multiply(2).subtract(5).getResult();
System.out.println(result); // 15.0
}
}
:::
特殊代码块
终端命令
# 安装依赖
npm install
# 启动开发服务器
npm run dev
# 构建生产版本
npm run build
# 运行测试
npm test
# 查看项目结构
tree -I node_modules
JSON配置
{
"name": "vuepress-demo",
"version": "1.0.0",
"description": "VuePress文档示例项目",
"scripts": {
"dev": "vuepress dev docs",
"build": "vuepress build docs",
"serve": "vuepress serve docs"
},
"dependencies": {
"vue": "^3.0.0",
"vuepress": "^2.0.0"
},
"devDependencies": {
"@vuepress/bundler-vite": "^2.0.0",
"@vuepress/theme-default": "^2.0.0"
}
}
YAML配置
# GitHub Actions 工作流
name: Deploy VuePress
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build
run: npm run build
- name: Deploy
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./docs/.vuepress/dist
代码差异对比
修改前后对比
// 修改前
function oldFunction(data) {
var result = [];
for (var i = 0; i < data.length; i++) {
if (data[i].active) {
result.push(data[i]);
}
}
return result;
}
// 修改后 - 使用现代JavaScript
function newFunction(data) {
return data.filter(item => item.active);
}
// 或者使用箭头函数
const filterActive = (data) => data.filter(item => item.active);
最佳实践
代码展示技巧
- 语法高亮: 始终指定正确的语言标识符
- 行号和高亮: 使用行号高亮重要代码行
- 代码组: 对于多语言实现,使用代码组展示
- 注释: 添加清晰的注释说明代码功能
- 完整示例: 提供可运行的完整代码示例
注意事项
- 确保代码示例的准确性和可运行性
- 避免在代码中包含敏感信息
- 保持代码风格的一致性
- 为复杂代码提供详细说明
支持的语言
VuePress支持多种编程语言的语法高亮:
- Web技术:
html,css,javascript,typescript,vue,jsx,tsx - 后端语言:
python,java,csharp,php,ruby,go,rust - 配置文件:
json,yaml,xml,toml,ini - 脚本语言:
bash,shell,powershell,batch - 数据库:
sql,mysql,postgresql - 其他:
markdown,dockerfile,nginx,apache
语言别名
某些语言有多个别名可以使用:
JavaScript: js, javascript
TypeScript: ts, typescript
Python: py, python
Shell: sh, bash, shell
C#: cs, csharp
