Vue库自有vuex

问题描述 投票:2回答:1

我做了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应用商店而不是库商店。这对我来说并不好,因为我需要在我需要库的每个应用中都有相同的actionmutations状态。

有没有一些选项可以让库商店在构建时 "打包 "库,这样库就会使用它自己的商店,而不是需要它的商店?

vue.js vuejs2 vuex vue-cli
1个回答
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功能,这可能是值得的。

© www.soinside.com 2019 - 2024. All rights reserved.