vuex

注意事项

  • vuex在单页面中会一直保留状态,直到单页面被销毁
  • 模块化其实和命名空间一样,mutation只能传入state和自定义参数,只能改变局部state。actions能够传入ctx(包含dispatch, commit, getters, rootGetters, state, rootState的对象)和自定义参数,用来操作多个mutation或actions、执行异步操作、操作其他模块的mutation或actions改变其他模块的state、访问自己或其他模块的getters和state。

state

定义

import Vuex from 'vuex'

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

引用

  • mapState返回一个对象,可以用...对象展开符展开到computed内使用
  • 参数为对象(3种方式)
import { mapState} from 'vuex'

  mapState({
    // 为了能够使用 `this` 获取局部状态,必须使用常规函数
    countPlusLocalState (state,getters) {    // 有两个参数,教程中只有第一个,不建议使用getters参数,它有自己的引用函数mapGetter
      return state.count + this.localCount
    },

    // 箭头函数可使代码更简练
    count: (state,getters) => state.count,

    // 传字符串参数 'count' 等同于 `state => state.count`
    countAlias: 'count',
  })
  • 参数为数组
mapState([
  // 映射 this.count 为 this.$store.state.count
  'count'
])
  • store直接使用
this.$store.state.count

getter计算属性

定义

  • 和state的名字可以重复
  • 可以引用其他getters
getters: {
  // ...
  doneTodosCount: (state, getters) => {
    return getters.doneTodos.length
  },
  doneTodosCount2 (state, getters) {
    return getters.doneTodos.length
  }
}
  • 可以通过让 getter 返回一个函数,来实现给 getter 传参。依然是在计算属性中引用,其实计算属性就是个函数来的,在绑定时自动执行返回结果,需要传参时写成v-bind:value = 'computedItem("参数")'
getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}

this.$store.getters.getTodoById(2)

引用

  • $store直接使用
this.$store.getters.getTodoById
  • 参数为数组
import { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
  // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}
  • 参数为对象,不像state,参数为对象时getters只有一种方法引用
mapGetters({
  // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
  doneCount: 'doneTodosCount'
})

mutation方法

定义

  • 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。
  • 只能传入一个自定义参数,如果要传入多个参数可以传入一个对象,然后逐个引用
mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}
  • 使用常量替代 mutation 事件类型,以使 linter 之类的工具发挥作用,同时把这些常量放在单独的文件中可以让你的代码合作者对整个 app 包含的 mutation 一目了然
export const SOME_MUTATION = 'SOME_MUTATION'

  mutations: {
    // 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
    [SOME_MUTATION] (state) {
      // mutate state
    }
  }

引用

  • 你不能直接调用一个 mutation handler。需要使用commit方法调用
// 传入两个参数,第一个为mutation名,第二个为传入mutation的参数
this.$store.commit('increment', {
  amount: 10
})

// 传入一个对象,type为mutation名,其余合并为对象作为参数
this.$store.commit({
  type: 'increment',
  amount: 10
})
  • 参数为数组映射到vue方法methods中
  methods: {
    ...mapMutations([
      'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`

      // `mapMutations` 也支持载荷(带参数)
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
    ]),
  • 参数为对象映射到vue方法methods中
// 对象
    ...mapMutations({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    })
  }

action 异步方法

定义

  • 可以传入参数
  actions: {
    increment (ctx, other) {
      ctx.commit('increment')
      let a = ctx.state.count + other
      ctx.dispatch('otherActions',canshu)
    }
  }
  • 可用于组合多个mutation(方法)
  actions: {
    increment ({ commit, dispatch, state, getter }) {
      commit('increment')
    }
  }
  • 组合多个 action
// 假设 getData() 和 getOtherData() 返回的是 Promise

actions: {
  async actionA ({ commit, dispatch, state, getter }) {
    commit('gotData', await getData())
  },
  async actionB ({ commit, dispatch, state, getter }) {
    await dispatch('actionA') // 等待 actionA 完成
    commit('gotOtherData', await getOtherData())
  }
}

引用

  • Action 通过 store.dispatch 方法触发
this.$store.dispatch('incrementAsync', {
  amount: 10
})

this.$store.dispatch({
  type: 'incrementAsync',
  amount: 10
})
  • 传入数组映射
// 数组
    ...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')`
    })

——————————————————————————————————————————————————————————

module

  • 以上为vuex的基础运用,该段落为模块化,用于在大型多人协作vuex中隔离key,避免冲突
  • 模块化其实只是对state进行了分组,方便管理而已。可以用于数据种类众多时进行归类。getter、mutation、action绑定在全局下,mutation只能操作局部state,getter和action增加了传参从而操作局部和全局的值

定义

  • 模块外依然可以设置state、mutations、actions、getters,只是在actions、getters中state=rootState,getters=rootGetters
const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: { ... },
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

定义getters(计算属性)

  • 可以通过让 getter 返回一个函数,来实现给 getter 传参。
  • 模块内部的 action、mutation 和 getter 是注册在全局命名空间(会有重名报错)
  • 参数依次为:模块内状态、全局计算属性、全局状态(嵌套状态可以从全局状态依次向下查找)、全局计算属性(实际上这里getters===rootGetters都是全局getters)
  getters: {
    sumWithRootCount (state, getters, rootState, rootGetters) {
      return state.count + rootState.count
    }
  }

定义mutation(方法)

  • 模块内部的 action、mutation 和 getter 是注册在全局命名空间(会有重名报错)
  • 模块内的mutations参数是局部state,只能操作局部state。全局的mutations能够操作全局所有的state
  mutations: {
    increment (state) {
      state.count++
    }
  },

定义actions(异步方法)

  • 可以操作其他模块的mutation 从而改变其他模块的state
  • 模块内部的 action、mutation 和 getter 是注册在全局命名空间(会有重名报错)
  • 参数内包含:模块内状态state、全局方法调用commit,全局状态rootState(嵌套状态可以从全局状态依次向下查找),全局异步方法调用dispatch,全局计算属性getter
  actions: {
    incrementIfOddOnRootSum ({ state, commit, rootState, dispatch }) {
      if ((state.count + rootState.count) % 2 === 1) {
        commit('increment')
      }
    }
  }

引用

  • 其他action、mutation 和 getter 的引用和基础一样
  • 对象引用state
mapState({    // 好像只能使用这种方法
    count(state,getters){
        return state.a.count
    }
})
  • store直接使用
this.$store.state.a // -> moduleA 的状态
this.$store.state.b // -> moduleB 的状态

——————————————————————————————————————————————————

命名空间

  • 模块内部的 action、mutation 和 getter 是注册在全局命名空间,添加 namespaced: true 的方式使其成为带命名空间,启用了命名空间的 getter 和 action 会收到局部化的 getter,dispatch 和 commit,而mutation依然只能改变局部state

命名空间state

定义

  • 命名空间的state定义和模块相同,只是引用方法不同

引用

  • 传入对象引用(3种方式)
computed: {
  ...mapState('some/nested/module', {
    a: state => state.a,
    b: 'b'
  })
},
  • 传入数组引用
methods: {
  ...mapState('some/nested/module', [
    'foo',    // -> foo:'foo'
    'bar'
  ])
}

命名空间getters(计算属性)

定义

  • 可以通过让 getter 返回一个函数,来实现给 getter 传参。
  • 局部状态、局部计算属性、全局状态(嵌套状态可以从全局状态依次向下查找)、全局计算属性
someGetter (state, getters, rootState, rootGetters) {
    ...
}

引用

  • 参数为数组
...mapGetters('some/nested/module', [
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  • 参数为对象
mapGetters('some/nested/module',{
  doneCount: 'doneTodosCount'
})

命名空间mutations

定义

  • 只能操作局部state
      namespaced: true,
      state: {
        count: 1
      },
      mutations: {
        addCount(state) {
          state.count += 1
        }
      }

引用

  • 参数为数组
    ...mapMutations('some/nested/module',[
      'increment',

      // `mapMutations` 也支持载荷(带参数)
      'incrementBy'
    ]),
  • 参数为对象
    ...mapMutations('some/nested/module',{
      add: 'increment'
    })

命名空间action(异步方法)

定义

  • 可以操作根及以下所有模块的mutations或actions从而改变其他模块的state
    namespaced: true,
    actions: {
      // 在这个模块中, dispatch(异步方法调用) 和 commit(方法调用) 也被局部化了
      // 他们可以接受 `root` 属性以访问根 dispatch 或 commit
      someAction ({ dispatch, commit, getters, rootGetters, state, rootState }) {
        getters.someGetter // -> 'foo/someGetter'
        rootGetters.someGetter // -> 'someGetter'

        dispatch('someOtherAction') // -> 'foo/someOtherAction'
        dispatch('someOtherAction', null, { root: true }) // -> 'someOtherAction'

        commit('someMutation') // -> 'foo/someMutation'
        commit('someMutation', null, { root: true }) // -> 'someMutation'

        // 操作根下的所有节点
        commit('foo/someMutation', null, { root: true }) // -> 'foo/someMutation'
      },
    }
  • 可以定义参数2,从而传入参数
actions: {
    someOtherAction (ctx, payload) { ... } // 第一个参数是vuex提供的,一个包含dispatch, commit, getters, rootGetters, state, rootState得对象,第二个参数为外部传入参数
}
  • 在带命名空间的模块注册全局 action
{
  actions: {
    someOtherAction ({dispatch}) {
      dispatch('someAction')
    }
  },
  modules: {
    foo: {
      namespaced: true,

      actions: {
        someAction: {
          root: true,  //在带命名空间的模块注册全局 action
          handler (namespacedContext, payload) { ... } // -> 'someAction'
        }
      }
    }
  }
}

引用

  • 参数为数组
    ...mapActions('some/nested/module',[
      'increment',

      // `mapActions` 也支持载荷:
      'incrementBy' 
    ]),
  • 参数为对象
    ...mapActions('some/nested/module',{
      add: 'increment'
    })

通用引用

  • 可以通过使用 createNamespacedHelpers 创建基于某个命名空间辅助函数
  • 通过store引用
const store = new Vuex.Store({
  modules: {
    account: {  //模块名
      namespaced: true,

      // 模块内容(module assets)
      state: { ... }, // 模块内的状态已经是嵌套的了,使用 `namespaced` 属性不会对其产生影响    this.$store.state.a直接范围模块下的state
      getters: {
        isAdmin () { ... } // -> this.$store.getters['account/isAdmin']
      },
      actions: {
        login () { ... } // -> this.$store.dispatch('account/login')
      },
      mutations: {
        login () { ... } // -> this.$store.commit('account/login')
      },

      // 嵌套模块
      modules: {
        // 继承父模块的命名空间
        myPage: {
          state: { ... },
          getters: {
            profile () { ... } // -> this.$store.getters['account/profile']
          }
        },

        // 进一步嵌套命名空间
        posts: {
          namespaced: true,

          state: { ... },
          getters: {
            popular () { ... } // -> this.$store.getters['account/posts/popular']
          }
        }
      }
    }
  }
})
原文地址:https://www.cnblogs.com/qq3279338858/p/9294520.html