vue库自己的vuex
Vue library own vuex
我制作了 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 应用程序商店而不是库商店。这对我不利,因为我需要在每个需要库的应用程序中使用相同的 actions/mutations/state。
是否有一些选项可以在构建时使图书馆商店 "packed" 与图书馆一起使用,这样图书馆将使用自己的商店,而不是需要它的商店?
我认为对于您的可共享 (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 应用程序,我用 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 应用程序商店而不是库商店。这对我不利,因为我需要在每个需要库的应用程序中使用相同的 actions/mutations/state。
是否有一些选项可以在构建时使图书馆商店 "packed" 与图书馆一起使用,这样图书馆将使用自己的商店,而不是需要它的商店?
我认为对于您的可共享 (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 功能,这可能是值得的。