我制作了 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 应用程序商店而不是库商店。这对我不利,因为我需要在需要库的每个应用程序中执行相同的操作/突变/状态。
是否有一些选项可以在构建时使图书馆商店与图书馆“打包”,以便图书馆将使用自己的商店,而不是需要它的商店?
最佳答案
我认为对于您的可共享 (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 选项卡的能力。
这也会阻止使用 mapAction
和 mapGetter
等函数,这就是我们在 beforeCreate 期间手动添加这些函数的原因。
或者,您可能想考虑从组件中移除 vuex,并使用 vue.Observable,这只是在组件之间共享可观察变量的一种方式。如果您不需要共享组件中的某些 vuex 功能,这可能是值得的。
关于vue.js - vue库自己的vuex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61641311/