Last active
February 6, 2018 15:42
-
-
Save jbbn/828ca890613ed2e1b4b3cd0d32072062 to your computer and use it in GitHub Desktop.
One Source of Truth - Redux + Vue + React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createStore, combineReducers, bindActionCreators} from 'redux' | |
import Revue from 'revue' | |
import { Provider, connect } from 'react-redux' | |
import React from 'react' | |
import ReactDOM from 'react-dom' | |
const counter = (state = 0, action) => { | |
switch(action.type) { | |
case 'increment': return state + 1 | |
case 'decrement': return state - 1 | |
default: return state | |
} | |
} | |
const actions = { | |
increment() { return { type: 'increment' } }, | |
decrement() { return { type: 'decrement' } } | |
} | |
// combine reducers | |
// and create the redux store | |
const reducer = combineReducers({counter}) | |
const store = createStore(reducer) | |
class _Counter extends React.Component { | |
render() { | |
const { increment, decrement, count } = this.props; | |
return ( | |
<div> | |
Current counter value: {count} | |
<button onClick={_ => increment()}>+</button> | |
<button onClick={_ => decrement()}>-</button> | |
</div> | |
) | |
} | |
} | |
const mapStateToProps = (state) => ({ count: state.counter }) | |
const mapDispatchToProps = (dispatch) => bindActionCreators(actions, dispatch) | |
const Counter = connect(mapStateToProps, mapDispatchToProps)(_Counter) | |
class App extends React.Component { | |
render() { | |
// let counter = store.getState().counter | |
return ( | |
<div> | |
<h2>React App</h2> | |
<Provider store={store}> | |
<Counter /> | |
</Provider> | |
</div> | |
) | |
} | |
} | |
ReactDOM.render(<App />, document.querySelector('[data-app="react-app"]')) | |
// create a revue store by binding redux store to Vue | |
const vueStore = new Revue(Vue, store, actions) | |
new Vue({ | |
el: '[data-app="vue-app"]', | |
data() { | |
return { count: this.$select('counter as count') } | |
}, | |
methods: { | |
handleIncrementA() { store.dispatch({type: 'increment'}) }, | |
handleIncrementB() { vueStore.dispatch(actions.increment()) }, | |
handleIncrementC() { | |
const {increment} = vueStore.actions | |
vueStore.dispatch(increment()) | |
} | |
} | |
}) | |
store.subscribe(_ => console.log(store.getState())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment