JuniorTree

Back

CardLink 组件使用指南

自动爬取链接元数据的卡片链接组件

CardLink 组件使用指南#

CardLink 是一个智能卡片链接组件,支持在构建时自动爬取链接的 Open Graph 元数据(标题、描述、图标等)。

✨ 特性#

  • 🤖 自动爬取元数据:从目标页面自动获取标题和描述
  • 构建时处理:在构建时完成所有爬取,不影响运行时性能
  • 🎨 多种样式变体:default、primary、minimal 三种风格
  • 🔗 智能后备:爬取失败时自动使用域名作为标题
  • 🌐 外部链接标识:自动添加外部链接图标

📖 基础用法#

自动爬取(推荐)#

只需提供链接,组件会自动爬取标题和描述:

<CardLink href="https://github.com/facebook/react" />
mdx

效果示例:

GitHub - facebook/react: The library for web and native user interfaces.

The library for web and native user interfaces. Contribute to facebook/react development by creating an account on GitHub. (github.com)

手动指定内容#

如果自动爬取的内容不理想,可以手动指定:

<CardLink
  href="https://example.com"
  title="自定义标题"
  description="这是自定义的描述文本,可以覆盖自动爬取的内容"
/>
mdx

效果示例:

自定义标题

这是自定义的描述文本,可以覆盖自动爬取的内容

🎨 样式变体#

Default(默认)#

<CardLink href="https://astro.build" />
mdx

Astro

Astro builds fast content sites, powerful web applications, dynamic server APIs, and everything in-between. (astro.build)

Primary(强调)#

<CardLink href="https://astro.build" variant="primary" />
mdx

Astro

Astro builds fast content sites, powerful web applications, dynamic server APIs, and everything in-between. (astro.build)

Minimal(简约)#

<CardLink href="https://astro.build" variant="minimal" />
mdx

Astro

Astro builds fast content sites, powerful web applications, dynamic server APIs, and everything in-between. (astro.build)

🔧 高级用法#

使用自定义图标#

<CardLink
  href="https://github.com"
  icon="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387..."
/>
mdx

内部链接#

对于站内链接,可以设置 external={false}

<CardLink
  href="/blog/my-post"
  title="我的文章"
  description="这是一篇内部文章"
  external={false}
/>
mdx

📦 多列布局#

结合 Tailwind CSS 创建多列卡片网格:

<div class="grid grid-cols-1 md:grid-cols-2 gap-4 not-prose">
  <CardLink href="https://astro.build" />
  <CardLink href="https://react.dev" />
  <CardLink href="https://vuejs.org" />
  <CardLink href="https://svelte.dev" />
</div>
mdx

效果:

📋 Props 参数#

参数类型默认值说明
hrefstring(必需)跳转链接
titlestringundefined手动指定标题(不指定则自动爬取)
descriptionstringundefined手动指定描述(不指定则自动爬取)
iconstringundefinedSVG path 字符串
variant'default' | 'primary' | 'minimal''default'样式变体
externalbooleantrue是否在新标签页打开
classstringundefined自定义类名

🚀 性能说明#

  • 构建时爬取:所有元数据在项目构建时获取,不增加运行时负担
  • 智能缓存:内置 LRU 缓存机制,避免重复请求同一 URL
  • 错误处理:爬取失败时优雅降级,使用域名作为后备标题
  • 只爬取 HTTPS:出于安全考虑,只爬取 HTTPS 链接

💡 最佳实践#

  1. 优先使用自动爬取:让组件自动获取标题和描述,保持内容新鲜
  2. 重要链接手动指定:对于特别重要的链接,建议手动指定标题和描述
  3. 合理使用变体:使用 primary 突出重点链接,minimal 用于次要链接
  4. 批量布局:使用 grid 布局展示多个链接时,记得添加 not-prose

🔍 与 LinkPreview 的区别#

项目中还有一个 LinkPreview 组件(来自 astro-pure),它们的区别:

特性CardLinkLinkPreview
布局紧凑卡片大型卡片(带图片)
用途快速链接跳转内容预览展示
图片不支持支持 Open Graph 图片
推荐场景参考资料列表文章开头展示引用

根据你的需求选择合适的组件!