3

I made Vue app which I build with vue-cli-service as a library.

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

It's building umd.js files which then I can release to npm and require in my other Vue apps.

In the library I have the following component:

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

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

My issue is that when I require this library to other vue(nuxt) app I can see this nuxt app store not the library store. This is not good for me because I would need to have same actions/mutations/state across every app where I require library.

Is there some option to make the library store "packed" with library when building so the library will use its own store, not the store where it's required to?

kasvith
  • 377
  • 5
  • 19
BT101
  • 3,666
  • 10
  • 41
  • 90

1 Answers1

3

I think for your sharable (umd) component, you may need to use a non-global store instance.

The downside is you'll have to update individual components to mount the store

Something like this:

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']
    },
}

because you'd no longer be using Vue.use(Vuex) you will likely loose the ability to use the Vuex tab in the browser Vue dev tool.

This also prevents use of functions such as mapAction and mapGetter, which is why we're adding those manually during the beforeCreate.

Alternatively, you might want to consider removing vuex from the component, and using vue.Observable which is just a way to share observable variables between components. If you don't need some of the vuex functionality in the shared component, this might be worthwhile.

Daniel
  • 34,125
  • 17
  • 102
  • 150
  • So basically in every component in library I need to import store and in `beforeCreate` hook attach it to `this`? Hmm maybe vue3 composition api would allow me some cleaner solution? – BT101 May 06 '20 at 18:46
  • 1
    Basically, yes. If you're using Vue 2.6+, `Vue.Observable` is a pretty clean solution in my opinion, it's got a smaller footprint than Vuex, but you'd still have to import and include in create/beforeCreate script. Here's a answer that show how it may work https://stackoverflow.com/questions/61531837/submit-values-from-multiple-components/61533909#61533909 – Daniel May 06 '20 at 21:07