InCuca/vue-standalone-component

Add vuex support

klarkc opened this issue · 7 comments

Add vuex support

@klarkc what is the best practice for handling this situation?

@IvoPereira I think it's not healthy to use vuex in such context, maybe you should use event bus instead, more about this.

of course you will need to change entry point of your component to a js file that instances the event bus, probably changing this file

In an usual case I would understand, however my main component has a lot of organized child components and passing props between all them may become a mess in the hand.

Vuex would make this so easier. Do you have at least any idea on how would you implement it?

One of things that Vuex wants to resolve is to centralize the state. So hiding the state inside the component is a bad pratice, what you can do is expose the state to who gonna use your component.

You can simple use internal state (this.$store.state), call actions and mutations and document this to who gonna use your component. Also you must expose default implementations for state, actions and mutations to who gonna use the component (you can expose a whole vuex module for this).

Or... You can ignore all best pratices and just import Vue + Vuex, use the Vuex plugin and expose the stateful component through entry file. Do expect strange things for this 🤣

One use case is this vuex plugin, that must have state, and expose things to user handle it.

In my specific use case, I am creating an UMD build to implement into my own project, so I don't have to worry with third-parties.

Just need a clean way to have separate components and implement them wherever I need in my existing project.

Isn't there a way to define some default properties for new Vue instances? That way I would be able to pass the store automatically from the component side whenever a new Vue instance is created.

@IvoPereira I think you can pass the store though a prop without issues, what you should not do is change the state directly, but if you are calling mutations and actions through $store prop there will be no problem.

On parent side you can just use the component normally:

Vue.use(Vuex);
const store = new Vuex.Store({ ... });
new Vue({template: '<my-child :store="$store" />', components: {myChild}, store)

On child:

{ props: { store: Object }, created: () => store.commit('change-from-child') }

Also on parent, you can just do this to generate the store for the components:

import {myChildStore} from 'my-child';

Vue.use(Vuex);
const store = new Vuex.Store({ modules: {myChildStore} });
new Vue({template: '<my-child :store="$store" />', components: {myChild}, store)

this way, you are not doing bad pratices, and user knows that there are internal state being managed by the child component.