• 状态管理vuex


    官方文档

    1. State

    vuex 使用单一状态树——是的,用一个对象就包含了全部的应用层级状态。

    1.1. 最简单的获取store实例中状态的方法

    // 创建一个 Counter 组件,在computed中返回。
    const Counter = {
      template: `<div>{{ count }}</div>`,
      computed: {
        count () {
          //vuex的状态存储是响应式的
          return store.state.count
        }
      }
    }
    

    1.2. mapState辅助函数

    我们可以使用 mapState 辅助函数帮助我们生成计算属性,将组件中的computed属性映射为 store 中的 state

    // 在单独构建的版本中辅助函数为 Vuex.mapState
    import { mapState } from 'vuex'
    
    export default {
      // ...
      computed: mapState({
        // 箭头函数可使代码更简练
        count: state => state.count,
    
        // 传字符串参数 'count' 等同于 `state => state.count`
        countAlias: 'count',
    
        // 为了能够使用 `this` 获取局部状态,必须使用常规函数
        countPlusLocalState (state) {
          return state.count + this.localCount
        }
      })
    }
    

    当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。

    computed: mapState([
      // 映射 this.count 为 store.state.count
      'count'
    ])
    

    2. Getter

    Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。

    2.1. 基本使用

    Getter 接受 state 作为其第一个参数:

    const store = new Vuex.Store({
      state: {
        todos: [
          { id: 1, text: '...', done: true },
          { id: 2, text: '...', done: false }
        ]
      },
      getters: {
        doneTodos: state => {
          return state.todos.filter(todo => todo.done)
        }
      }
    })
    

    Getter 会暴露为 store.getters 对象:

    store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
    

    Getter 也可以接受其他 getter 作为第二个参数:

    getters: {
      // ...
      doneTodosCount: (state, getters) => {
        return getters.doneTodos.length
      }
    }
    store.getters.doneTodosCount // -> 1
    

    我们可以很容易地在任何组件中使用它:

    computed: {
      doneTodosCount () {
        return this.$store.getters.doneTodosCount
      }
    }
    

    你也可以通过让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用。

    getters: {
      // ...
      getTodoById: (state) => (id) => {
        return state.todos.find(todo => todo.id === id)
      }
    }
    store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
    

    2.2. mapGetters 辅助函数

    我们可以使用 mapGetter 辅助函数帮助我们生成计算属性,将组件中的computed属性映射为 store 中的 getter

    import { mapGetters } from 'vuex'
    
    export default {
      // ...
      computed: {
      // 使用对象展开运算符将 getter 混入 computed 对象中
        ...mapGetters([
          'doneTodosCount',
          'anotherGetter',
          // ...
        ])
      }
    }
    

    如果你想将一个 getter 属性另取一个名字,使用对象形式:

    mapGetters({
      // 映射 `this.doneCount` 为 `store.getters.doneTodosCount`
      doneCount: 'doneTodosCount'
    })
    

    3. Mutation

    3.1. 基本使用

    更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:

    const store = new Vuex.Store({
      state: {
        count: 1
      },
      mutations: {
        increment (state) {
          // 变更状态
          state.count++
        }
      }
    })
    

    当触发一个类型为 increment 的 mutation 时,调用此函数。”要唤醒一个 mutation handler,你需要以相应的 type 调用 store.commit 方法:

    store.commit('increment')
    

    3.2. 提交载荷

    3.2.1. 普通提交方式

    1.传入额外的参数,即 mutation 的 载荷(payload):

    // ...
    mutations: {
      increment (state, n) {
        state.count += n
      }
    }
    store.commit('increment', 10)
    

    2.载荷是一个对象

    // ...
    mutations: {
      increment (state, payload) {
        state.count += payload.amount
      }
    }
    store.commit('increment', {
      amount: 10
    })
    

    3.2.2. 对象风格的提交方式

    提交 mutation 的另一种方式是直接使用包含 type 属性的对象:

    mutations: {
      increment (state, payload) {
        state.count += payload.amount
      }
    }
    
    store.commit({
      type: 'increment',
      amount: 10
    })
    

    3.3. 使用常量替代 Mutation 事件类型

    这样可以使 linter 之类的工具发挥作用,同时把这些常量放在单独的文件中可以让你的代码合作者对整个 app 包含的 mutation 一目了然:

    // mutation-types.js
    export const SOME_MUTATION = 'SOME_MUTATION'
    // store.js
    import Vuex from 'vuex'
    import { SOME_MUTATION } from './mutation-types'
    
    const store = new Vuex.Store({
      state: { ... },
      mutations: {
        // 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
        [SOME_MUTATION] (state) {
          // mutate state
        }
      }
    })
    

    3.4. Mutation 必须是同步函数

    注意:一条重要的原则就是要记住 mutation 必须是同步函数。

    3.5. 在组件中提交 Mutation

    你可以在组件中使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations 辅助函数将组件中的methods映射为 store.commit 调用(需要在根节点注入 store)。

    import { mapMutations } from 'vuex'
    
    export default {
      // ...
      methods: {
        ...mapMutations([
          'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
    
          // `mapMutations` 也支持载荷:
          'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
        ]),
        ...mapMutations({
          add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
        })
      }
    }
    

    4. Action

    Action 类似于 mutation,不同在于:

    • Action 提交的是 mutation,而不是直接变更状态。
    • Action 可以包含任意异步操作。

    4.1 基本用法

    让我们来注册一个简单的 action:

    const store = new Vuex.Store({
      state: {
        count: 0
      },
      mutations: {
        increment (state) {
          state.count++
        }
      },
      actions: {
        increment (context) {
          context.commit('increment')
        }
      }
    })
    

    Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。

    4.2 分发action

    Action 通过 store.dispatch 方法触发:

    store.dispatch('increment')
    

    显然直接分发mutation更方便,但是mutation 必须同步执行,Action 则不受这个限制

    我们可以在action内部执行异步操作

    actions: {
      incrementAsync ({ commit }) {
        setTimeout(() => {
          commit('increment')
        }, 1000)
      }
    }
    

    Actions 支持同样的载荷方式和对象方式进行分发:

    // 以载荷形式分发
    store.dispatch('incrementAsync', {
      amount: 10
    })
    
    // 以对象形式分发
    store.dispatch({
      type: 'incrementAsync',
      amount: 10
    })
    

    4.3 在组件中分发action

    你在组件中使用 this.$store.dispatch('xxx') 分发 action,或者使用 mapActions 辅助函数将组件的methods映射为 store.dispatch 调用(需要先在根节点注入 store):

    import { mapActions } from 'vuex'
    
    export default {
      // ...
      methods: {
        ...mapActions([
          'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
    
          // `mapActions` 也支持载荷:
          'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
        ]),
        ...mapActions({
          add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
        })
      }
    }
    

    5. Module

    由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

    5.1. 基本使用

    为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

    const moduleA = {
      state: { ... },
      mutations: { ... },
      actions: { ... },
      getters: { ... }
    }
    
    const moduleB = {
      state: { ... },
      mutations: { ... },
      actions: { ... }
    }
    
    const store = new Vuex.Store({
      modules: {
        a: moduleA,
        b: moduleB
      }
    })
    
    store.state.a // -> moduleA 的状态
    store.state.b // -> moduleB 的状态
    

    5.2 模块的局部状态

    对于模块内部的 mutation 和 getter,接收的第一个参数是模块的局部状态对象。

    const moduleA = {
      state: { count: 0 },
      mutations: {
        increment (state) {
          // 这里的 `state` 对象是模块的局部状态
          state.count++
        }
      },
    
      getters: {
        doubleCount (state) {
          return state.count * 2
        }
      }
    }
    

    同样,对于模块内部的 action,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState:

    const moduleA = {
      // ...
      actions: {
        incrementIfOddOnRootSum ({ state, commit, rootState }) {
          if ((state.count + rootState.count) % 2 === 1) {
            commit('increment')
          }
        }
      }
    }
    

    对于模块内部的 getter,根节点状态会作为第三个参数暴露出来:

    const moduleA = {
      // ...
      getters: {
        sumWithRootCount (state, getters, rootState) {
          return state.count + rootState.count
        }
      }
    }
    

    6 实战分析

    参考官方购物车实例

    以menu为了分析下思路

    1.app.js

    import 'babel-polyfill'
    import Vue from 'vue'
    import App from './components/App.vue'
    import store from './store'  //步骤1
    import { currency } from './currency'
    
    Vue.filter('currency', currency)
    
    new Vue({
      el: '#app',
      store,  //步骤2
      render: h => h(App)
    })
    
    

    做了两步 : 引入store 并绑定到根实例上

    2.store/index.js

    import Vue from 'vue'
    import Vuex from 'vuex'
    import * as actions from './actions'
    import * as getters from './getters'
    import fruit from './modules/fruit';
    
    Vue.use(Vuex)
    
    const store = new Vuex.Store({
      actions,
      getters,
      modules: {
        fruit,
      },
    })
    
    export default store;
    

    3.store/nutation-types.js

    export const FRUIT_SHOW = "FRUIT_SHOW"
    export const FRUIT_HIDE = "FRUIT_HIDE"
    
    

    4.store/modules/fruit.js

    import {FRUIT_SHOW,FRUIT_HIDE,} from '../../store/mutation-types'
    
    export default {
      state: {
        appearence: false,
      },  
    
      mutations: {
        [FRUIT_HIDE](state) {
          state.appearence = false
        },  
        [FRUIT_SHOW](state) {
          state.appearence = true
        },  
      },  
    
      actions: {
        hideFruit({commit}) {
          commit(FRUIT_HIDE)
        },  
        showFruit({commit}) {
          commit(FRUIT_SHOW)
        },  
      },  
      getters: {
        fruitState:state => state.appearence,
      }
    }
    
    

    5.使用方法

    <template>
        <div>
            <p v-if="appearence">apple</p>
            <el-button type="primary" @click="showApple">显示</el-button>
            <el-button  @click="hideApple">隐藏</el-button>
        </div>
    </template>
    
    <script>
    
    import { mapState } from 'vuex';
    import { mapGetters } from 'vuex';
    
    export default {
        data () {
          return {
          }
        },
    
        methods: {
            showApple(){
                //使用commit触发mutations
                this.$store.commit('FRUIT_SHOW');
    
                //使用dispatch触发actions,action中使用commit触发mutations
                //this.$store.dispatch('showFruit'); 
            },                                       
            hideApple(){                             
                //this.$store.commit('FRUIT_HIDE');  
                this.$store.dispatch('hideFruit');   
            },                                       
        },
        
        //使用getters
        computed: mapGetters({
            appearence: 'fruitState',
        }),
     
         /**                                         
        //使用 state
        computed: mapState({
            //appearence: appearence, 这样是错误,少了一层fruit
            appearence: state => state.fruit.appearence,
        }),   
              
        //另一种表示方法
        computed:{ 
             ...mapState({
                appearence: state => state.fruit.appearence,
            })
         },   
         **/
      
        mounted() {    
            //使用state获取状态
            console.log(this.$store.state.fruit.appearence);
            //使用getters获取状态
            console.log(this.$store.getters.fruitState);
        },             
    
    }
    
    </script>
    
    

    6.另一种定义getters的方法

    store/modules/fruit.js

    import {
      FRUIT_SHOW,
      FRUIT_HIDE,
    } from '../../store/mutation-types'
    
    export default {
      state: {
        appearence: false,
      },  
    
      mutations: {
        [FRUIT_HIDE](state) {
          state.appearence = false
        },  
        [FRUIT_SHOW](state) {
          state.appearence = true
        },  
      },  
    
      actions: {
        hideFruit({commit}) {
          commit(FRUIT_HIDE)
        },  
        showFruit({commit}) {
          commit(FRUIT_SHOW)
        },  
      },  
      
      //这里不在定义getters
    }
    
    

    store/getters.js

    const fruitState = (state) => state.fruit.appearence;
    
    export {
        fruitState,
    }
    
    
  • 相关阅读:
    服务管理器
    自动启动管理器
    进程管理器
    进程模块查看器
    无DLL远程注入
    远程DLL注入
    U盘免疫
    WSAAsyncSelect Demo
    select Demo
    校正系统时间
  • 原文地址:https://www.cnblogs.com/redirect/p/8436036.html
Copyright © 2020-2023  润新知