ktsn / vuex-class

Binding helpers for Vuex and vue-class-component
MIT License
1.73k stars 86 forks source link

feat: Enhance namespace helper with generic powered StateBindingHelper #54

Open hikerpig opened 5 years ago

hikerpig commented 5 years ago

This PR adds some generic types to enhance StateTransformer and namespace for better type inference.

tarik02 commented 4 years ago

I think that you should implement the same for mapActions and mapMutations too. As you can read here https://vuex.vuejs.org/api/#mapactions, if you pass function instead of action/mutation name as object's value, then function will be called with dispatch/commit for actions/mutations, and rest of args.

Example:

methods: {
    ...mapActions({
        login(dispatch, username, password) {
            dispatch('login', { username, password })
        }
    })
}
tarik02 commented 4 years ago

This can be implemented in easier way:

diff --git a/src/bindings.ts b/src/bindings.ts
index f0c9231..f665791 100644
--- a/src/bindings.ts
+++ b/src/bindings.ts
@@ -93,7 +93,13 @@ function createBindingHelper (
         componentOptions[bindTo] = {}
       }

-      const mapObject = { [key]: map }
+      let mapObject: any
+      if (componentOptions.methods && componentOptions.methods[key]) {
+        mapObject = { [key]: componentOptions.methods[key] }
+        delete componentOptions.methods[key]
+      } else {
+        mapObject = { [key]: map }
+      }

       componentOptions[bindTo]![key] = namespace !== undefined
         ? mapFn(namespace, mapObject)[key]

After this, you can use it like this:

@Action
login(dispatch, username, password) {
    dispatch('login', { username, password })
}

The solution you used for state can't be normally used for actions and mutations because it is usually needed to use this in action/mutation "enhancer".

But my solution has a disadvantage: it can't be normally typed.