讓Vue也可以使用Redux的方法
上周末看Vuex源碼,突發(fā)靈感,為什么都是Vuex啊。
于是蛋疼一下午寫了一個插件來幫助Vue可以使用Redux
Vue-with-Redux
這是一個用于幫助Vue使用Redux管理狀態(tài)的插件。Redux是一個非常流行的狀態(tài)管理工具。vue-with-redux為大家提供一個可以在Vue環(huán)境下使用Redux的途徑。這回帶來不同的開發(fā)體驗。
開始
首先你需要通過如下命令安裝vue-with-redux
npm install -save vue-with-redux
運行Demo
git clone https://github.com/ryouaki/vue-with-redux.git npm install npm run serve
Usage
需要像下面這樣改造你的入口文件:
// 有可能是你的entry.js文件
... // 這里是你引入的其它包
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')
下面是一個actionCreate函數(shù):
export function test() {
return {
type: 'TEST'
}
}
export function asyncTest() {
return (dispatch, getState) => {
setTimeout( () => {
console.log('New:', getState());
dispatch({type: 'TEST'});
console.log('Old', getState());
}, 100);
}
}
Note: 你并不需要使用redux-thunk,因為Vue-with-Redux已經(jīng)提供了對異步處理的支持.
這是一個reducer的例子:
function reduce (state = { count: 0 }, action) {
switch(action.type) {
case 'TEST':
state.count++;
return state;
default:
return state;
}
}
export default {
reduce
};
Vue的組件例子:
<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
},
// 你必須在這里預先定義你訂閱的Redux中的狀態(tài)。否則編譯模版會報錯。
data() {
return {
reduce: {}
}
},
methods: {
clickHandler1() {
this.dispatch({type: 'TEST'});
},
clickHandler2() {
this.dispatch(test());
},
clickHandler3() {
this.dispatch(asyncTest());
},
// 你必須實現(xiàn)一個mapReduxState函數(shù),用于告訴Vue-with-Redux你需要訂閱哪些redux中的狀態(tài)
// [ state ] 參數(shù)就是redux狀態(tài)樹的根。
mapReduxState(state) {
return {
reduce: state.reduce
}
},
}
}
</script>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Vue組件間通信方法總結(父子組件、兄弟組件及祖先后代組件間)
這篇文章主要給大家介紹了關于Vue組件間通信的相關資料,其中包括父子組件、兄弟組件及祖先后代組件間的通信,文中通過示例代碼介紹的非常詳細,對大家學習或者使用Vue具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2019-04-04

