這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)?lái)有關(guān)如何在Vue中使用Redux,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
首先你需要通過(guò)如下命令安裝vue-with-redux
npm install -save vue-with-redux
運(yùn)行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')
下面是一個(gè)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,因?yàn)閂ue-with-Redux已經(jīng)提供了對(duì)異步處理的支持.
這是一個(gè)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)。否則編譯模版會(huì)報(bào)錯(cuò)。 data() { return { reduce: {} } }, methods: { clickHandler1() { this.dispatch({type: 'TEST'}); }, clickHandler2() { this.dispatch(test()); }, clickHandler3() { this.dispatch(asyncTest()); }, // 你必須實(shí)現(xiàn)一個(gè)mapReduxState函數(shù),用于告訴Vue-with-Redux你需要訂閱哪些redux中的狀態(tài) // [ state ] 參數(shù)就是redux狀態(tài)樹(shù)的根。 mapReduxState(state) { return { reduce: state.reduce } }, } } </script>Vue的優(yōu)點(diǎn)
Vue具體輕量級(jí)框架、簡(jiǎn)單易學(xué)、雙向數(shù)據(jù)綁定、組件化、數(shù)據(jù)和結(jié)構(gòu)的分離、虛擬DOM、運(yùn)行速度快等優(yōu)勢(shì),Vue中頁(yè)面使用的是局部刷新,不用每次跳轉(zhuǎn)頁(yè)面都要請(qǐng)求所有數(shù)據(jù)和dom,可以大大提升訪問(wèn)速度和用戶體驗(yàn)。
上述就是小編為大家分享的如何在Vue中使用Redux了,如果剛好有類(lèi)似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
網(wǎng)站標(biāo)題:如何在Vue中使用Redux-創(chuàng)新互聯(lián)
文章起源:http://www.rwnh.cn/article24/djhoce.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供云服務(wù)器、網(wǎng)站改版、虛擬主機(jī)、網(wǎng)站營(yíng)銷(xiāo)、企業(yè)網(wǎng)站制作、品牌網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容