Vue-Redux-Mixin-Generator
A simple function that returns a reusable object of redux dispatch action functions thats pluggable to Vue's mixins option.
Installation
npm install --save vue-mixin-generator
Why Should I Use This?
I built this to help myself and others to reduce the amount of code necessary to get up and running with redux. I love the concept but I found it tedious to create actions, reducers and then have to create Vue methods that call the store.dispatch()
method. Knowing how simple it was to import a plain object and plug it into Vue's mixins object, I decided to create this to generate reuseable methods that can be used all over an application.
Usage
A typical redux flow looks like:
Actions
const SET_USER = 'SET_USER';const setUser = type: SET_USER user; const CLEAR_USER = 'CLEAR_USER';const clearUser = type: CLEAR_USER user; const UPDATE_USER_INFO = 'UPDATE_USER_INFO';const updateUser = type: UPDATE_USER_INFO user;
Reducers
//Import all the actions; { }
Dilema
Now in all of your Vue files have:
import store from './services/store.js
import {setUser, updateUser} from './actions.js
and your Vue's methods options becomes full of functions that aren't reuseable anywhere else in your application.
EX:
{ return user: store } methods: { store; } { store }
Options
prefix: optional actions: required array of functions store: required Store Class
`import store from './services/store.js``import {setUser, updateUser} from './actions.js`// No Function Name Prefixconst UserMixin =actions: setUser updateUserstore: store// Prefixed Functionsconst UserMixin =prefix: 'store'actions: setUser updateUserstore: store
Solution
Create mixins that allow you to resuse methods that call store.dispatch()
importable across your entire app.
// Store & Actions;; // Mixin Generator; /** Create New Mixin Object*/const UserMixin = /** Mixin Object Created*/ UserMixin = methods: { store } { store } { store }
Using Together With Vue Component
template: mixins: UserMixin { return user: store error: '' } // Now methods can be 100% focused on data manipulation methods: { return namelength > 0 ? this : false } { $http }
Verdict
Now you have the methods necessary for dispatching new states that is importable to any component. I know some might be confused on how i'm calling the methods I created from reVueMixinGen
, When you attach a mixin to a component the methods become available via this
just like any other method in the $vm scope.
EX:
import UserMixin from './mixins.js'
{
template: require('./path/to/file.html'),
mixins: [UserMixin],
data() {
return {
user: {
firstName: 'Sean',
lastName: 'Parsons'
}
}
},
attached() {
// this.storeSetUser is equivalent to:
// store.dispatch(setUser(user))
// Except without the import of both store.js and actions.js in each component.
this.storeSetUser(this.user);
}
}