vuepress2.x 使用vue组件

MicLon原创2022年6月11日
大约 1 分钟

记一次踩坑,由于vuepress2.x官方文档open in new window的markdown中并未提及如何使用Vue组件。

因此,下意识的去看看v1.x的文档,可以发现,在v1.x中,可以使用自定义vue组件来实现markdown的功能。

而方法也十分简单,约束大于配置,只需要在.vuepress文件中新建components文件夹,然后把你的组件放在里面即可。

按着这种方式试了几个回合,未果。

于是又去翻看v1迁移v2文档open in new window,在里面发现,在v1中自动注册component的方式已经被废弃了!

提示

在该目录下的文件不会被自动注册为 Vue 组件。

你需要使用 @vuepress/plugin-register-componentsopen in new window,或者在 .vuepress/client.{js,ts} 中手动注册你的组件。

原来是需要安装插件对自定义组件进行选项配置了,而不是和v1一样,一股脑的全给register。既然是官方支持的插件,那就去官方插件文档中找到这个插件的使用方法。

插件安装教程:官方文档open in new window

pnpm i -D @vuepress/plugin-register-components@next
const { registerComponentsPlugin } = require('@vuepress/plugin-register-components')
const { path } = require('@vuepress/utils')

module.exports = {
  plugins: [
      registerComponentsPlugin({
          componentsDir: path.resolve(__dirname, './components'),
      })
  ],
}

完整的配置项可以参考以上文档。

接下来看看成果:

我是markdown中的vue组件

附上vue组件代码:

<template>
  <div style="border: #0a7bf4 1px solid">
    <h3>{{ msg }}</h3>
    <button @click="num++">点我点我:{{num}}</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      num: 0,
      msg: "我是markdown中的vue组件"
    };
  }
}
</script>
Loading...