vue.jsvuejs3vuepress

vuepress2: how to get Vue instance so I can use third part vue plugin?


I am trying to use v-wave in VuePress 2 (the VuePress powered by Vue 3)

I followed the docs, try to use the v-wave as a local plugin of the VuePress 2

.vuepress/config.js

const vwave = require('path/to/v-wave.js');

module.exports = {
    plugins: [
        (options, app) => {
            app.use(vwave); // the `app` is a instance of VuePress not Vue
            return {name: 'v-wave'};
        }
    ]
};

But it didn't work, because the app isn't the Vue instance but the VuePress.

How can I install v-wave to make it work in VuePress 2?

Thanks a lot!


Solution

  • It seems there's no config API in VuePress specifically to configure the client app. However, the Plugin API supports configuring a root component in the client app with the clientAppRootComponentFiles property.

    For example, this config points to .vuepress/RootComponent.vue:

    // .vuepress/config.js
    const path = require('path')
    
    module.exports = {
      plugins: [
        {
          name: 'root-component-setup',
          clientAppRootComponentFiles: path.resolve(__dirname, './RootComponent.vue'),
        }
      ]
    }
    

    In that component file, use the Composition API's getCurrentInstance() to access the application instance's use() to globally install the v-wave plugin:

    // .vuepress/RootComponent.vue
    <template>
      <slot></slot>
    </template>
    
    <script>
    import { getCurrentInstance, defineComponent } from 'vue'
    import VWave from 'v-wave'
    
    export default defineComponent({
      setup() {
        getCurrentInstance().appContext.app.use(VWave)
      }
    })
    </script>
    

    demo