Skip to content
0

vue中2种方式导入自定义组件

vue中2种方式导入自定义组件

以下2种方式为在teek 学习中总结而来。

背景

image-20250913082416703

image-20250913082427875

bash
帮我生成一个XXXX的vue3版本的组件,不要使用Tailwind CSS,样式直接使用普通css写在组件内。

image-20250913082451883

image-20250913082505999

方式1:在index.ts文件中注册

  • 效果(时光大佬写的友链)

image-20250912204553036

  • 配置方式

(1)新建组件与文件结构

在 VitePress 主题目录下创建友链组件相关文件,结构如下:

ts
.vitepress
├─ theme
│  ├─ components
│  │  ├─ SLink
│  │  │  ├─ index.vue
│  │  │  └─ LinkItem.vue
│  │  ├─ MyLayout.vue
│  │  ├─ Twikoo.vue
│  └─ index.ts
└─ config.mts

编写友链组件代码

友链组件分为两部分:index.vue(负责分组展示与留言区)和 LinkItem.vue(单个友链卡片),完整代码如下:

详细信息
vue
<template>
  <div class="my-links-container">
    <!-- 页面主标题区域 -->
    <div class="my-links-title">
      <h1>{{ title }}</h1>
    </div>
……
/* 留言卡片悬停效果 */
.message-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 28px rgba(0, 0, 0, 0.12);
}
</style>
vue
<template>
  <div class="link-item-card">
    <a :href="data.link" :title="data.name" target="_blank" rel="noopener">
      <!-- 头像 -->

……
  box-orient: vertical;
  -webkit-line-clamp: 2; /* 兼容旧版 */
  line-clamp: 2; /* 标准属性(核心) */
  overflow: hidden;
  line-height: 1.4;
}
</style>

(2)注册组件

ts
import SLink from "./components/SLink/index.vue";

export default {
  enhanceApp({ app }) {
    // 注册全局组件
    app.component("friend-link", SLink);
  },
};

(3)使用方法

  • frontmatter 中设置 layoutfriend-link,启用友链布局模式
  • 建议设置 sidebar: false,界面更美观
  • 设置 comments: false 可关闭底部评论区

新建如下文件:

使用模板
md
---
date: 2025-09-03 02:06:02
layout: friend-link
title: 我的友链
sidebar: false
permalink: /about/friend-links
article: false
comment: false
copyright: false
links:
  - title: 个人站点
    #desc: "建站中学习和使用了以下博客/网站的技术和分享,特别鸣谢!💖"
    list:
      - name: One
        link: https://onedayxyy.cn/
        avatar: https://img.onedayxyy.cn/images/Teekwebsite/xyy-logo.webp
        irregular: true
        descr: 明心静性,爱自己(基于vitepress) 
  - title: 漂亮的博客
    # desc: "聚集众多优秀独立博客,随机传送 \U0001F680"
    list:
      - name: 王嘉祥
        link: https://blog.jiaxiang.wang/
        avatar: https://img.onedayxyy.cn/images/Teekwebsite/blog.jiaxiang.wang.webp
        descr: 唱响科普和人生兴事,分享科技与美好生活(rust写的zola主题,移植于张洪heo)
        irregular: true        
categories:
  - 关于
coverImg: https://img.onedayxyy.cn/images/TeekCover/1.webp
---

(4)组件效果

http://localhost:5173/about/friend-links

image-20250911230431903

方式2:在md文件中注册

  • 效果

image-20250912205153240

  • 配置

创建组件:

image-20250912205222504

注册组件:

image-20250912205305090

md
---
title: 关于我
date: 2025-01-04 11:19:48
permalink: /about/me
layout: page
categories:
  - 更多
tags:
  - 关于我
author:
  name: One
  link: https://wiki.onedayxyy.cn/
sidebar: false
article: false
comment: false
articleTopTip: false
articleBottomTip: false
copyright: false
coverImg: https://img.onedayxyy.cn/images/TeekCover/8.webp
---

<script setup>
import About from '../.vitepress/theme/components/About.vue'
</script>

<About />

结束。

最近更新