【问题标题】:Vue library own vuexVue库自己的vuex
【发布时间】:2020-08-21 18:38:14
【问题描述】:

我制作了 Vue 应用程序,我使用 vue-cli-service 作为库构建。

"bundle": "vue-cli-service build --target lib --name search_widget \"src/components/index.js\""

它正在构建 umd.js 文件,然后我可以将其发布到 npm 并在我的其他 Vue 应用程序中使用。

在库中,我有以下组件:

<template>
  <div>hello {{ $store.state }}</div>
</template>

<script>
export default {
  name: "HelloWorld"
};
</script>

我的问题是,当我需要这个库到其他 vue(nuxt) 应用程序时,我可以看到这个 nuxt 应用程序商店而不是库商店。这对我不利,因为我需要在需要库的每个应用程序中都具有相同的操作/突变/状态。

是否有一些选项可以在构建时使图书馆商店与图书馆“打包”,以便图书馆将使用自己的商店,而不是需要的商店?

【问题讨论】:

    标签: vue.js vuejs2 vuex vue-cli


    【解决方案1】:

    我认为对于您的可共享 (umd) 组件,您可能需要使用非全局存储实例。

    缺点是您必须更新单个组件才能挂载商店

    类似这样的:

    import store from "./store"
    
    export default {
        name: "form",
        // ...stuff...
        beforeCreate() {
            this.$store = store(); // No way around this
            // register getter
            this.myGetter = this.$store.getters['myGetter']
            // register action
            this.myAction = this.$store.getters['myAction']
        },
    }
    

    因为您将不再使用 Vue.use(Vuex),您可能会失去在浏览器 Vue 开发工具中使用 Vuex 选项卡的能力。

    这也阻止了mapActionmapGetter 等函数的使用,这就是我们在 beforeCreate 期间手动添加这些函数的原因。

    或者,您可能想考虑从组件中删除 vuex,并使用 vue.Observable,这只是在组件之间共享可观察变量的一种方式。如果您不需要共享组件中的某些 vuex 功能,这可能是值得的。

    【讨论】:

    • 所以基本上在库中的每个组件中我都需要导入存储并在beforeCreate 钩子中将其附加到this?嗯,也许 vue3 composition api 可以让我得到一些更清洁的解决方案?
    • 基本上,是的。如果您使用的是 Vue 2.6+,Vue.Observable 在我看来是一个非常干净的解决方案,它的占用空间比 Vuex 小,但您仍然需要导入并包含在 create/beforeCreate 脚本中。这是一个显示它如何工作的答案stackoverflow.com/questions/61531837/…
    猜你喜欢
    • 2022-06-20
    • 2018-02-23
    • 2019-09-20
    • 2019-06-01
    • 1970-01-01
    • 2019-10-19
    • 2020-02-20
    • 2019-09-25
    • 2021-09-12
    相关资源
    最近更新 更多