Last weekend to see Vuex source code, suddenly inspired, why are Vuex ah. So I wrote a plugin to help Vue use Redux

Gayhub Url

Vue-with-Redux

This is a plug-in that helps Vue manage state using Redux. Redux is a very popular state management tool. Vue-with-redux provides a way to use Redux in a VUE environment. This brings a different development experience.

start

First you need to install vue-with-redux with the following command

  npm install -save vue-with-redux
Copy the code

Run the Demo

  git clone https://github.com/ryouaki/vue-with-redux.git
  npm install
  npm run serve
Copy the code

Usage

You need to modify your entry file as follows:

  // It could be your entry.js file.// Here are the other packages you introduced
  import VuexRedux from 'vue-with-redux';
  import { makeReduxStore } from 'vue-with-redux';
  import reduces from 'YOUR-REDUCERS';
  import middlewares from 'REDUX-MIDDLEWARES';

  Vue.use(VuexRedux);

  let store = makeReduxStore(reduces, [middlewares]);

  new Vue({
    store,
    render: h= > h(App)
  }).$mount('#app')
Copy the code

Here is an actionCreate function:

  export function test() {
    return {
      type: 'TEST'}}export function asyncTest() {
    return (dispatch, getState) = > {
      setTimeout( (a)= > {
        console.log('New:', getState());
        dispatch({type: 'TEST'});
        console.log('Old', getState());
      }, 100); }}Copy the code

Note: You don’t need to use redux-thunk because vue-with-redux already provides support for asynchronous processing.

Here is a Reducer example:

  function reduce (state = { count: 0 }, action) {
    switch(action.type) {
      case 'TEST':
        state.count++;
        return state;
      default:
        returnstate; }}export default {
    reduce
  };
Copy the code

Examples of Vue components:

<template> <div> <button @click="clickHandler1">Action Object</button> <button @click="clickHandler2">Sync Action</button> <button @click="clickHandler3">Async Action</button> <p>{{reduce.count}}</p> </div> </template> <script>  import { test, asyncTest } from './.. /actions'; Export default {name: 'HelloWorld', props: {MSG: String}, // Here you must pre-define the state in the Redux you subscribed to. Otherwise, the compilation template will report an error. data() { return { reduce: {} } }, methods: { clickHandler1() { this.dispatch({type: 'TEST'}); }, clickHandler2() { this.dispatch(test()); }, clickHandler3() { this.dispatch(asyncTest()); }, // you must implement a mapReduxState function that tells vue-with-redux which Redux states you need to subscribe to. // The [state] parameter is the root of the Redux state tree. mapReduxState(state) { return { reduce: state.reduce } }, } } </script>Copy the code