让Vue也可以使用Redux
生活随笔
收集整理的這篇文章主要介紹了
让Vue也可以使用Redux
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
上周末看Vuex源碼,突發(fā)靈感,為什么都是Vuex啊。 于是蛋疼一下午寫(xiě)了一個(gè)插件來(lái)幫助Vue可以使用Redux
Gayhub Url
Vue-with-Redux
這是一個(gè)用于幫助Vue使用Redux管理狀態(tài)的插件。Redux是一個(gè)非常流行的狀態(tài)管理工具。vue-with-redux為大家提供一個(gè)可以在Vue環(huán)境下使用Redux的途徑。這回帶來(lái)不同的開(kāi)發(fā)體驗(yàn)。
開(kāi)始
首先你需要通過(guò)如下命令安裝vue-with-redux
npm install -save vue-with-redux運(yùn)行Demo
git clone https://github.com/ryouaki/vue-with-redux.gitnpm installnpm run serveUsage
需要像下面這樣改造你的入口文件:
// 有可能是你的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>更多專業(yè)前端知識(shí),請(qǐng)上 【猿2048】www.mk2048.com
總結(jié)
以上是生活随笔為你收集整理的让Vue也可以使用Redux的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: WeScale 技术篇 —— mpvue
- 下一篇: vsCode 设置vue 保存自动格式化