Vuex和Redux是两个流行的JavaScript状态管理库,它们有一些相似之处,但也有一些区别。
区别:
优缺点: Vuex的优点:
Vuex的缺点:
Redux的优点:
Redux的缺点:
适用场景:
原理:
示例: Vuex示例:
- // store.js
- import Vue from 'vue';
- import Vuex from 'vuex';
-
- Vue.use(Vuex);
-
- const store = new Vuex.Store({
- state: {
- count: 0,
- },
- mutations: {
- increment(state) {
- state.count++;
- },
- },
- });
-
- export default store;
-
- // App.vue
- <template>
- <div>
- <p>{{ count }}p>
- <button @click="increment">Incrementbutton>
- div>
- template>
-
- <script>
- import { mapState, mapMutations } from 'vuex';
-
- export default {
- computed: {
- ...mapState(['count']),
- },
- methods: {
- ...mapMutations(['increment']),
- },
- };
- script>
Redux示例:
- // store.js
- import { createStore } from 'redux';
-
- const initialState = {
- count: 0,
- };
-
- function reducer(state = initialState, action) {
- switch (action.type) {
- case 'INCREMENT':
- return {
- count: state.count + 1,
- };
- default:
- return state;
- }
- }
-
- const store = createStore(reducer);
-
- export default store;
-
- // App.js
- import React from 'react';
- import { useSelector, useDispatch } from 'react-redux';
-
- const App = () => {
- const count = useSelector((state) => state.count);
- const dispatch = useDispatch();
-
- const increment = () => {
- dispatch({ type: 'INCREMENT' });
- };
-
- return (
- <div>
- <p>{count}p>
- <button onClick={increment}>Incrementdiv>
- );
- };
-
- export default App;