目录
- 引言
- 前置环境
- 使用 vue 组件
- 安装插件
- 配置插件
- 创建 vue 组件
- 使用 vue 组件
引言
只是单纯的用 vuepress
写个 markdown 文档,的确会处处受限,满足不了定制化的样式和功能,有时只是简单的修改下某个页面,或者做些组件演示的内容,而不是开发一整套主题。所以研究下如何在项目中使用 vue
组件还有非常有必要的,毕竟也没那么难。
前置环境
- node 环境
node v16.13.0
- VuePress 版本
VuePress v2.0.0-beta.48
每个版本的使用方式还是有些差异的,尤其是 1.x
与 2.x
,所以在阅读的时候尽量与自己所用的版本对比下,避免不必要的试错。
使用 vue 组件
安装插件
在 Vuepress2.x
中需要安装 @vuepress/plugin-register-components 插件并做好配置,而在Vuepress1.0中,md 文件能自动识别导出的.vue
文件。
yarn add @vuepress/plugin-register-components@next // 或者 npm i -D @vuepress/plugin-register-components@next
配置插件
config.js
中配置修改如下:
? 官方配置项文档
const { registerComponentsPlugin } = require('@vuepress/plugin-register-components') module.exports = { plugins: [ registerComponentsPlugin({ // 配置项 }), ], }
我本地的配置文件的部分内容:
const path = require("path"); const { defaultTheme } = require('vuepress'); const { docsearchPlugin } = require('@vuepress/plugin-docsearch') // ======================引入插件==================================== const { registerComponentsPlugin } = require('@vuepress/plugin-register-components') // ======================引入插件 End================================ const navbar = require('./navbar'); const sidebar = require('./sidebar'); module.exports = { base: '/', lang: 'zh-CN', title: '前端技术栈', description: '前端白皮书', head: [ ['link', { rel: 'manifest', href: '/manifest.webmanifest' }], ['meta', { name: 'theme-color', content: '#3eaf7c' }] ], alias: { '@pub': path.resolve(__dirname, './public'), }, markdown: { importCode: { handleImportPath: (str) => str.replace(/^@src/, path.resolve(__dirname, 'src')), }, extractTitle: true }, // ======================配置插件==================================== plugins: [ registerComponentsPlugin({ // 配置项 componentsDir: path.resolve(__dirname, './components') }) ], // ======================配置插件 End================================= theme: defaultTheme({ // URL logo: 'https://vuejs.org/images/logo.png', // 顶部导航 navbar: navbar, // 侧边栏 sidebar: sidebar, sidebarDepth: 2, // e'b将同时提取markdown中h2 和www.cppcns.com h3 标题,显示在侧边栏上。 lastUpdated: true // 文档更新时间:每个文件git最后提交的时间 }) }
创建 vue 组件
在.vuepress
文件夹中新建components文件夹,里面存放vue组件,文件结构如下:
├─.vuepress │ └─ components │ │ └─ Card.vue │ └─ config │ │ └─ navbar.js │ │ └─ sidebar.js │ └─ public │ │ └─ images │ └─ config.js
至此md文件就能无需引入即可自动识别.vuepress/components/
下所有的vue组件了。继续完成下面的步骤,就可以看到项目中使用的效果。
Card.vue
文件内容如下,这个组件个人可以因需而定,这里只做个参照,和后面的效果对应上。key
这里没有设置业务 ID 暂且使用 k
来代替。
<template> <div class="g-card-link"> <div v-for="(item,k) in value" class="g-card-item" :key="k"> <a :href="http://www.cppcns.com/wangluo/javascript/item.link" rel="external nofollow" target="_blank" :title="item.title">{{item.title}}</a> </div> </div> </template> <script setup> import { ref, defineProps } from 'vue'; const props = defineProps({ defaultValue:String }) const value = http://www.cppcns.com/wangluo/javascript/ref(props.defaultValue);