Skip to content

Instantly share code, notes, and snippets.

@exah
Last active April 4, 2016 16:14
Show Gist options
  • Save exah/b1c150c605b1d1c0891f to your computer and use it in GitHub Desktop.
Save exah/b1c150c605b1d1c0891f to your computer and use it in GitHub Desktop.
Simple Vue + Redux mixin
import { bindActionCreators } from 'redux';
export default (
store,
actions,
stateKey = 'state',
actionsKey = '$actions'
) => {
const getFrozenState = () => Object.freeze( store.getState() );
return {
data: () => ({
[stateKey]: getFrozenState(),
}),
methods: {
updateState() {
this.$set( stateKey, getFrozenState() );
},
},
created() {
this[actionsKey] = bindActionCreators( actions, store.dispatch );
this.unsubscribe = store.subscribe(
() => this.$set( stateKey, getFrozenState() )
);
},
beforeDestroy() {
this.unsubscribe();
},
}
}

Features:

  • Inside .vue components you can access to shared state with this.state;
  • Dispatch Redux actions directly in store or use this.$actions.actionName(value)

store/index.js:

import { createStore, combineReducers } from 'redux';
import * as reducers from 'reducers';
import * as actions from 'actions';
import createReduxStoreMixin from 'vue-redux-store-mixin';

export const store = createStore( combineReducers( reducers ) );

export default reduxStoreMixin = createReduxStoreMixin(store, actions);

index.js:

import Vue from 'vue';
import { reduxStoreMixin } from 'store';

Vue.mixin(reduxStoreMixin);

app.vue:

<template>
  <div class='app'> {{ state.msg }} </div>
</template>
<script>
  export default {
    ready() {
      this.$actions.setMessage('Hello World!');
    }
  }
</script>

http://www.webpackbin.com/NJZza92Tx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment