首页 > 解决方案 > vuepress2:如何获取 Vue 实例以便我可以使用第三方 vue 插件?

问题描述

我正在尝试在VuePress 2中使用v-wave(由 Vue 3 提供支持的 VuePress)

我遵循了文档,尝试将其v-wave用作本地插件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'};
        }
    ]
};

但它不起作用,因为app它不是 Vue 实例而是 VuePress。

如何安装v-wave以使其在 VuePress 2 中工作?

非常感谢!

标签: vue.jsvuejs3vuepress

解决方案


VuePress 中似乎没有专门用于配置客户端应用程序的配置 API。clientAppRootComponentFiles但是,插件 API 支持在客户端应用程序中使用属性配置根组件。

例如,此配置指向.vuepress/RootComponent.vue

// .vuepress/config.js
const path = require('path')

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

在该组件文件中,使用 Composition APIgetCurrentInstance()访问应用程序实例use()以全局安装v-wave插件:

// .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>

演示


推荐阅读