如何在Vue中使用Redux

2023-06-09,

这期内容当中小编将会给大家带来有关如何在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>

Vue的优点

Vue具体轻量级框架、简单易学、双向数据绑定、组件化、数据和结构的分离、虚拟DOM、运行速度快等优势,Vue中页面使用的是局部刷新,不用每次跳转页面都要请求所有数据和dom,可以大大提升访问速度和用户体验。

上述就是小编为大家分享的如何在Vue中使用Redux了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注本站行业资讯频道。

《如何在Vue中使用Redux.doc》

下载本文的Word格式文档,以方便收藏与打印。