這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān)如何在Vue中使用Redux,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

首先你需要通過如下命令安裝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
},
// 你必須在這里預(yù)先定義你訂閱的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的優(yōu)點Vue具體輕量級框架、簡單易學(xué)、雙向數(shù)據(jù)綁定、組件化、數(shù)據(jù)和結(jié)構(gòu)的分離、虛擬DOM、運行速度快等優(yōu)勢,Vue中頁面使用的是局部刷新,不用每次跳轉(zhuǎn)頁面都要請求所有數(shù)據(jù)和dom,可以大大提升訪問速度和用戶體驗。
上述就是小編為大家分享的如何在Vue中使用Redux了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
網(wǎng)站標(biāo)題:如何在Vue中使用Redux-創(chuàng)新互聯(lián)
文章起源:http://www.chinadenli.net/article24/djhoce.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供云服務(wù)器、網(wǎng)站改版、虛擬主機(jī)、網(wǎng)站營銷、企業(yè)網(wǎng)站制作、品牌網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容