针对vue组件,编写对应的组件文档
- 使用
vuepress
直接通过markdown文件去动态生成对应的组件演示和代码预览以及说明。
准备工作
- 先安装
vuepress
,npm i vuepress -D
。 - 接着安装
vuepress-plugin-demo-container
,npm i vuepress-plugin-demo-container -D
。 - 整理项目目录:
root
docs
.vuepress
config.js
enhanceApp.js
ui
test.md
bussiness
test.md
src
... package.json
中新增命令。"scripts": { "docs:dev": "vuepress dev docs", "docs:build": "vuepress build docs" }
主要配置
-
config.js
。module.exports = { title: 'Test Component', // 左上角的标题 description: 'Just a test demo.', // meta内容 plugins: ['demo-container'], // 引用的`vuepress-plugin-demo-container`插件 themeConfig: { // 主题配置,可以直接看文档 sidebar: [ // 侧边栏配置 { title: 'UI组件', path: '/UI/', collapsable: true, children: [ '/UI/test' ] }, { title: '业务组件', path: '/Function/', collapsable: true, children: [ '/Function/test' ] } ] } }
-
enhanceApp.js
。// 通过该文件,把需要用的组件进行全局的注册,因为在markdown中的文件不能使用import引入组件,必须要提前注册好全局的组件 import HelloWorld from '../../src/components/HelloWorld.vue'; export default ({ Vue }) => { Vue.component('HelloWorld', HelloWorld); } // 昨天发现同时注册多个组件的时候好像有问题,只好换一种方式来实现,将组件通过一个文件抛出,然后使用Vue.use去完成组件的注册 import components from '../../src/components/index.js'; const customPlugin = {}; customPlugin.install = function(Vue, options = {}) { const { components } = options; for(let key in components) { if(Object.prototype.hasOwnProperty.call(components, key)) { Vue.component(key, components[key]); } } } export default ({ Vue }) => { Vue.use(customPlugin { components }) }
-
test.md
。::: demo [some comments]
开始标志,可以在demo后面加一些注释,:::
结尾标志,用了这个开始结尾标志的就会自动去渲染它的示例以及代码块,script
标签中一定要有export default {}
,不然不会展示它的示例效果。为了展示这块代码,所以把三个`号分开了,实际写的时候是要挨在一起的。### Test2 ::: demo ` ` `vue <template> <HelloWorld msg="Nice to meet you, Jane!" /> </template> <script> export default {} </script> ` ` ` :::
查看效果
npm run docs:dev
,直接查看你的组件文档,至此,简单的组件预览文档已经可以基本使用了,其它需要的功能可以自己对着官网的api
去配置。