ignisrzeus
5 months ago
1203
3
Vue

Vuex Module Reuse Best Practices

Posted 5 months ago by ignisrzeus

Good Day Laracasts!

I posted a few days ago regarding the application of Vuex module reuse. While I am able to create unique namespaces for each module, it is to my surprise that they actually share properties -- which defeats the purpose of reusing Vuex modules (at least for my context).

Below is a code from my "Account Component"

    beforeDestroy() {
        this.$store.unregisterModule(this.namespace);
    },
    beforeCreate() {
        var id = this.$route.params.id;
        var namespace = "account-" + id;
        return new Promise((resolve, reject) => {
            resolve(this.$store.registerModule(namespace, accountModule));
        }).then((response) => {
            this.$store.dispatch(namespace + "/storeItem", id);
        });
    },

As you can see above, I am creating a new AccountModule everytime I create this component based on the router parameters, and proceed to unregister the module when the component is destroyed.

For every instance of the accountModule, I expect to be given a fresh copy of the accountModule:

  state: {
        item: null,
        
        loading: true,
        show_return_modal: false,
        show_reject_modal: false,
        show_remarks_modal: true,

Situation: - When I load "somelink.com/accounts/1", and i change the value of "show_remarks_modal" to false through a mutation, it works as intended. However, when I load "somelink.com/accounts/2", and I check the value of "show_remarks_modal", it is now changed to false even if I did not mutate it within the page. This led me to believe that I'm only creating a new module, but i am actually referencing to the same store.

After much research, I came across a discussino on github that has the exact same problem as I do:

https://github.com/vuejs/vuex/issues/615

However, I still do not understand how to implement this approach because I am not exactly sure what createModule() does given the answer above.

Sorry it took so long, but to conclude, I have these questions in mind - How can I create reuse modules with the same "template" without each affecting each other? - Am I creating unique namespaces correctly? - Am I destroying modules correctly?

I'm very interested in mastering Vuex, so Im hoping you guys can help me around here.

Thank you Laracasts!

Please sign in or create an account to participate in this conversation.