首页 > 解决方案 > Vue2 如何将多个组件导出为使用 Vuex 的库?

问题描述

我正在尝试将 Vue.js 2 项目导出为包含多个组件的库。

以此为例我设法导出了一个组件。

在我的“库”项目中,我在 main.js 中导出:

import TestButton from "@/components/TestButton";
import store from "@/store";

export default {
  install(Vue, options) {
    if (!options || !options.store) {
      throw new Error("Please initialise plugin with a Vuex store.");
    }

    options.store.registerModule("testLibrary", store);

    Vue.component("test-button", TestButton);
  }
};

我通过vue-cli-service build --target lib --name testlib src/main.js

通过在 npm 上发布npm publish --access-public

然后导入另一个 Vue 2 项目。

在 main.js 我有:

[...]
new Vue({
  store,
  render: (h) => h(App),
}).$mount("#app");

import TestButton from "my-test-library";

Vue.use(TestButton, { store });

然后我可以成功地使用<test-button></test-button> 我需要的任何组件,而 Vuex Store 有一个工作的“testLibrary”模块。

现在的问题是如何在第一个应用程序中导出多个组件并在第二个应用程序中导入。

我找到了很多关于的例子,比如这个,但是我无法让它工作。

例如,在我正在尝试的图书馆应用程序中

import TestButton from "@/components/TestButton";
import AnotherComponent "@/components/AnotherComponent";

import store from "@/store";
export default {
  install(Vue, options) {
    if (!options || !options.store) {
      throw new Error("Please initialise plugin with a Vuex store.");
    }

    options.store.registerModule("testLibrary", store);

    Vue.component("test-button", TestButton);
    Vue.component("another-component", AnotherComponent);
  }
};

在第二个应用程序中,我正在尝试类似

[...]
import { TestButton, AnotherComponent } from "my-test-library";

但是无论我尝试什么语法,似乎第二个应用程序在构建时都会进入循环并且不起作用。

知道这是怎么做的吗?

标签: vue.jsvuejs2vue-componentvuex

解决方案


推荐阅读