Vuex和Redux都是状态管理库,它们的工作原理和区别如下:
下面是一个简单的Vuex示例,用于管理一个购物车中的商品数量:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
cartCount: 0
},
mutations: {
increment (state) {
state.cartCount++;
},
decrement (state) {
state.cartCount--;
}
},
actions: {
addToCart ({ commit }, product) {
commit('increment');
},
removeFromCart ({ commit }, product) {
commit('decrement');
}
}
});
export default store;
在组件中,可以通过this.$store
来访问Vuex的state、getter、mutation和action。例如,以下代码将显示购物车中的商品数量:
Your cart has {{ cartCount }} items.
下面是一个简单的Redux示例,用于管理一个计数器的状态:
首先,需要安装Redux和React-Redux库:
npm install redux react-redux
创建一个Redux store:
import { createStore } from 'redux';
import rootReducer from './reducers';
const store = createStore(rootReducer);
编写一个reducer来管理计数器的状态:
import { INCREMENT, DECREMENT } from './actions';
const counterReducer = (state = 0, action) => {
switch (action.type) {
case INCREMENT:
return state + 1;
case DECREMENT:
return state - 1;
default:
return state;
}
};
定义一些actions来改变计数器的状态:
export const increment = () => ({ type: 'INCREMENT' });
export const decrement = () => ({ type: 'DECREMENT' });
在React组件中使用Redux store:
import { connect } from 'react-redux';
import { increment, decrement } from './actions';
const Counter = ({ count, onIncrement, onDecrement }) => (
Count: {count}
);
const mapStateToProps = (state) => ({ count: state });
const mapDispatchToProps = { increment, decrement };
export default connect(mapStateToProps, mapDispatchToProps)(Counter);