Skip to content
Go back

在 Astro 博客中嵌入 Vue3 和 React19 组件

Published:  at  10:00 PM

在 Astro 博客中嵌入 Vue3 和 React19 组件

作为前端工程师,我们经常需要在博客中展示各种技术概念和交互效果。Astro 的 Islands Architecture 让我们可以在同一个博客中同时使用多个前端框架,这为技术博客提供了无限可能。

为什么选择 Astro?

Astro 的核心优势在于它的 Islands Architecture

实战演示

Vue3 组件:交互式代码演示器

这是一个使用 Vue3 Composition API 构建的代码演示组件:

Vue3 响应式示例

Vue3 Composition API 演示

✨ 响应式数据

🧮 计算属性

🎯 TypeScript

React19 组件:状态管理演示

这是一个展示 React19 新特性的计数器组件:

React19 状态管理演示

0

操作历史:

技术实现细节

1. 项目配置

首先需要安装相关依赖:

# 安装 Astro 集成
pnpm add @astrojs/vue @astrojs/react

# 安装框架依赖
pnpm add vue@^3.4.0 react@^19.0.0 react-dom@^19.0.0
pnpm add @types/react@^19.0.0 @types/react-dom@^19.0.0

然后在 astro.config.ts 中添加集成:

import { defineConfig } from 'astro/config'
import vue from '@astrojs/vue'
import react from '@astrojs/react'

export default defineConfig({
  integrations: [
    vue(),
    react(),
    // ... 其他集成
  ],
})

2. 组件开发

Vue 组件使用 Composition API 和 TypeScript:

<script setup lang="ts">
import { ref } from 'vue'

interface Props {
  title: string
  code: string
}

defineProps<Props>()

const showCode = ref(false)
</script>

<template>
  <div class="component">
    <!-- 组件内容 -->
  </div>
</template>

React 组件使用最新的 hooks 和 TypeScript:

import { useState, useEffect } from 'react'

interface Props {
  initialValue?: number
  title?: string
}

export default function MyComponent({ initialValue = 0 }: Props) {
  const [state, setState] = useState(initialValue)
  
  return (
    <div>
      {/* 组件内容 */}
    </div>
  )
}

3. 在 Markdown 中使用

在博客文章的 frontmatter 中导入组件:

---
title: "我的博客文章"
---

import MyVueComponent from "../../components/MyVueComponent.vue"
import MyReactComponent from "../../components/MyReactComponent.tsx"

# 文章标题

这里是内容...

<MyVueComponent client:load />
<MyReactComponent client:load />

Islands 加载策略

Astro 提供了多种客户端加载策略:

指令说明使用场景
client:load页面加载时立即运行重要的交互组件
client:idle页面空闲时运行非关键交互
client:visible元素可见时运行长页面中的组件
client:media媒体查询匹配时运行响应式组件

最佳实践

1. 性能优化

2. 开发体验

3. 用户体验

总结

Astro 的 Islands Architecture 为前端工程师的博客提供了完美的解决方案:

这种架构让我们可以在保持博客高性能的同时,为读者提供丰富的交互体验。无论是展示代码示例、演示技术概念,还是创建教学工具,都能轻松实现。


💡 提示:你可以访问 /framework-demo 页面查看更多组件演示,或者在这个项目的基础上开始构建你自己的技术博客!


Suggest Changes

Previous Post
Vue 和 React 组件演示
Next Post
How to use Git Hooks to set Created and Modified Dates