当前位置: 移动技术网 > IT编程>脚本编程>vue.js > 让Vue也可以使用Redux的方法

让Vue也可以使用Redux的方法

2018年05月29日  | 移动技术网IT编程  | 我要评论

圣战屠龙,湖北高考减招,海南新闻在线

上周末看vuex源码,突发灵感,为什么都是vuex啊。

于是蛋疼一下午写了一个插件来帮助vue可以使用redux

gayhub url

vue-with-redux

这是一个用于帮助vue使用redux管理状态的插件。redux是一个非常流行的状态管理工具。vue-with-redux为大家提供一个可以在vue环境下使用redux的途径。这回带来不同的开发体验。

开始

首先你需要通过如下命令安装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函数:

 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已经提供了对异步处理的支持.

这是一个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中的状态。否则编译模版会报错。
 data() {
  return {
  reduce: {}
  }
 },
 methods: {
  clickhandler1() {
  this.dispatch({type: 'test'});
  },
  clickhandler2() {
  this.dispatch(test());
  },
  clickhandler3() {
  this.dispatch(asynctest());
  },
  // 你必须实现一个mapreduxstate函数,用于告诉vue-with-redux你需要订阅哪些redux中的状态
  // [ state ] 参数就是redux状态树的根。
  mapreduxstate(state) { 
  return {
   reduce: state.reduce
  }
  },
 }
 }
 </script>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网