(生产)vuex - 状态管理

参考:https://vuex.vuejs.org/zh-cn/

安装

  • 直接下载 / CDN 引用

 

https://unpkg.com/vuex
在 Vue 以后引入 vuex 会进行自动安装:
<script src="/path/to/vue.js"></script>
<script src="/path/to/vuex.js"></script>html

 

  • NPM

 

npm install vuex --savevue

 

 

State

单一状态树

Vuex 使用 单一状态树 —— 是的,用一个对象就包含了所有的应用层级状态。至此它便做为一个『惟一数据源(SSOT)』而存在。这也意味着,每一个应用将仅仅包含一个 store 实例。单一状态树让咱们可以直接地定位任一特定的状态片断,在调试的过程当中也能轻易地取得整个当前应用状态的快照web

使用

    store.jsvuex

import Vue from 'vue'
import Vuex from 'vuex'
import * as actions from './actions'
import * as getters from './getters'
import state from './state'
import mutations from './mutations'
Vue.use(Vuex)
export default new Vuex.Store({
  actions,
  getters,
  state,
  mutations
})npm

 

main.jsapi

   import store from './store'数组

new Vue({
  el: '#app',
  store,
  ...............
})websocket

    // store 实例会注入到根组件下的全部子组件中,且子组件能经过 this.$store访问到app

 

mapState 辅助函数

须要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余异步

mapState 辅助函数帮助咱们生成计算属性

// 引入
import { mapState } from 'vuex'

computed: mapState({
  // 箭头函数可以使代码更简练
  count: state => state.count,

  // 等同于 `state => state.count`
  countAlias: 'count',

  // 等同于 `name => state.name`
  name,

  // 为了可以使用 `this` 获取局部状态,必须使用常规函数
  countPlusLocalState (state) {
    return state.count + this.localCount
  }
})

 

//自己又有单独的属性的状况
computed: {
  //内部的计算属性
  selfattr() {

  },
  ...mapState({
    count,
    name
  })
}

 

Getters

有时候咱们须要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数

return this.$store.state.todos.filter(todo => todo.done).length

多个组件须要用到此属性,咱们要么复制这个函数,或者抽取到一个共享函数而后在多处导入它 —— 不管哪一种方式都不是很理想

Vuex 容许咱们在 store 中定义『getters』(能够认为是 store 的计算属性)。Getters 接受 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)
    }
  }
})

  Getters 会暴露为 store.getters 对象

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

 

  Getters 也能够接受其余 getters 做为第二个参数

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

 

  咱们能够很容易地在任何组件中使用它:

this.$store.getters.doneTodosCount

 

mapGetters 辅助函数

mapGetters 辅助函数仅仅是将 store 中的 getters 映射到局部计算属性:

语法参照state

computed: {
  ...mapGetters([
    'doneTodosCount',
    'anotherGetter'
  ])
}

 

 

Mutations

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

例子: 

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

//不能直接调用一个 mutation handler , 须要调用 store.commit 方法

store.commit('increment')

 

store.commit 传入额外的参数

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

 

对象风格的提交方式

  store.commit({ type: 'increment', amount: 10 })

  mutations: { increment (state, payload) { state.count += payload.amount } }

 

Mutations 需遵照 Vue 的响应规则

  1. 最好提早在你的 store 中初始化好全部所需属性。
  2. 当须要在对象上添加新属性时,你应该 使用 Vue.set(obj, 'newProp', 123), 或者 -
  3. 以新对象替换老对象。例如,利用 stage-3 的对象展开运算符咱们能够这样写:state.obj = { ...state.obj, newProp: 123 }

 

使用常量替代 Mutation 事件类型(规范)

// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'

// store.js
import { SOME_MUTATION } from './mutation-types'

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

    .........
  }
}

  

mutation 必须是同步函数

  

提交 Mutations

普通提交:

this.$store.commit('xxx') 提交 mutation

使用 mapMutations 提交:

import { mapMutations } from 'vuex'
export default {
  methods: {
    ...mapMutations([
      'increment' // 映射 this.increment() 为 this.$store.commit('increment')
    ]),
    ...mapMutations({
      add: 'increment' // 映射 this.add() 为 this.$store.commit('increment')
    })
  }
}

 

 

Actions

Action 相似于 mutation,不一样在于:
Action 提交的是 mutation,而不是直接变动状态。
Action 能够包含任意异步操做

例子:

mutations: {
  increment (state) {
    state.count++
  }
},
actions: {
  increment (context) {
    context.commit('increment')
  }
}

Action 函数接受一个与 store 实例具备相同方法和属性的 context 对象,所以你能够调用 context.commit 提交一个 mutation,或者经过 context.state 和 context.getters 来获取 state 和 getters。当咱们在以后介绍到 Modules时,你就知道 context 对象为何不是 store 实例自己了

 

 参数解构 来简化代码

    actions: {

      increment ({ commit }) {

         commit('increment')

      }

    }

  

分发 Action

Action 经过 store.dispatch 方法触发:store.dispatch('increment') ; 咱们能够在 action 内部执行异步操做

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

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

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

 

 mapActions 辅助函数

import { mapActions } from 'vuex'
methods: {
  ...mapActions([
    'increment' // 映射 this.increment() 为 this.$store.dispatch('increment')
  ]),
  ...mapActions({
    add: 'increment' // 映射 this.add() 为 this.$store.dispatch('increment')
  })
}

 

组合 Actions

Action 一般是异步的,那么如何知道 action 何时结束呢?更重要的是,咱们如何才能组合多个 action,以处理更加复杂的异步流程?

store.dispatch 能够处理被触发的action的回调函数返回的Promise,而且store.dispatch仍旧返回Promise

例子:

actions: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  }
}

如今你能够:
store.dispatch('actionA').then(() => {
  ........
})

在另一个 action 中也能够:
actions: {
  actionB ({ dispatch, commit }) {
    return dispatch('actionA').then(() => {
      commit('someOtherMutation')
    })
  }
}

 

 async / await 组合

// 假设 getData() 和 getOtherData() 返回的是 Promise
actions: {
  async actionA ({ commit }) {
    commit('gotData', await getData())
  },
  async actionB ({ dispatch, commit }) {
    await dispatch('actionA') // 等待 actionA 完成
    commit('gotOtherData', await getOtherData())
  }
}

 

Modules

应用的全部状态会集中到一个比较大的对象。当应用变得很是复杂时,store 对象就有可能变得至关臃肿

以上问题,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 的状态

 

模块的局部状态

对于模块内部的 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
    }
  }
}

 

命名空间

默认状况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的——这样使得多个模块可以对同一 mutation 或 action 做出响应。若是但愿你的模块更加自包含或提升可重用性,你能够经过添加 namespaced: true的方式使其成为命名空间模块。当模块被注册后,它的全部 getter、action 及 mutation 都会自动根据模块注册的路径调整命名 , 例如:

const store = new Vuex.Store({
  modules: {
    account: {
      namespaced: true,
      state: { ... }, // 模块内的状态已是嵌套的了,使用 `namespaced` 属性不会对其产生影响
      getters: {
        isAdmin () { ... } // -> getters['account/isAdmin']
      },
      actions: {
        login () { ... } // -> dispatch('account/login')
      },
      mutations: {
        login () { ... } // -> commit('account/login')
      },

      
      modules: {     // 嵌套模块
        myPage: {   // 继承父模块的命名空间
          getters: {
            profile () { ... } // -> getters['account/profile']
          }
        },
        posts: {  // 进一步嵌套命名空间
          namespaced: true,
          getters: {
            popular () { ... } // -> getters['account/posts/popular']
          }
        }
      }
    }
  }
})

 

在命名空间模块内访问全局内容(Global Assets)

若是你但愿使用全局 state 和 getter,rootState 和 rootGetter 会做为第三和第四参数传入 getter,也会经过context 对象的属性传入 action。

若须要在全局命名空间内分发 action 或提交 mutation,将 { root: true } 做为第三参数传给 dispatch 或 commit便可。

modules: {
  foo: {
    namespaced: true,
    getters: {
      // 在这个模块的 getter 中,`getters` 被局部化了
      // 你可使用 getter 的第四个参数来调用 `rootGetters`
      someGetter (state, getters, rootState, rootGetters) {
        getters.someOtherGetter // -> 'foo/someOtherGetter'
        rootGetters.someOtherGetter // -> 'someOtherGetter'
      },
      someOtherGetter: state => { ... }
    },
    actions: {
      // 在这个模块中, dispatch 和 commit 也被局部化了
      // 他们能够接受 `root` 属性以访问根 dispatch 或 commit
      someAction ({ dispatch, commit, getters, rootGetters }) {
        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'
      },
      someOtherAction (ctx, payload) { ... }
    }
  }
}

 

带命名空间的绑定函数

当使用 mapStatemapGettersmapActions 和 mapMutations 这些函数来绑定命名空间模块时,写起来可能比较繁琐:

computed: {
  ...mapState({
    a: state => state.some.nested.module.a,
    b: state => state.some.nested.module.b
  })
},
methods: {
  ...mapActions([
    'some/nested/module/foo',
    'some/nested/module/bar'
  ])
}

对于这种状况,你能够将模块的空间名称字符串做为第一个参数传递给上述函数,上面的例子能够简化为:

computed: {
  ...mapState('some/nested/module', {
    a: state => state.a,
    b: state => state.b
  })
},
methods: {
  ...mapActions('some/nested/module', [
    'foo',
    'bar'
  ])
}

 

 

插件

Vuex 的 store 接受 plugins 选项,这个选项暴露出每次 mutation 的钩子。Vuex 插件就是一个函数,它接收 store 做为惟一参数:

const myPlugin = store => {
  // 当 store 初始化后调用
  store.subscribe((mutation, state) => {
    // 每次 mutation 以后调用
    // mutation 的格式为 { type, payload }
  })
}

而后像这样使用:

const store = new Vuex.Store({
  plugins: [myPlugin]
})

 

下面是个大概例子

export default function createWebSocketPlugin (socket) {
  return store => {
    socket.on('data', data => {
      store.commit('receiveData', data)
    })
    store.subscribe(mutation => {
      if (mutation.type === 'UPDATE_DATA') {
        socket.emit('update', mutation.payload)
      }
    })
  }
}
const plugin = createWebSocketPlugin(socket)

const store = new Vuex.Store({
  state,
  mutations,
  plugins: [plugin]
})

 

严格模式

开启严格模式,仅需在建立 store 的时候传入 strict: true

在严格模式下,不管什么时候发生了状态变动且不是由 mutation 函数引发的,将会抛出错误。这能保证全部的状态变动都能被调试工具跟踪到

不要在发布环境下启用严格模式!

构建工具来处理这种状况

const store = new Vuex.Store({

  strict: process.env.NODE_ENV !== 'production'

})

 

表单处理

当在严格模式中使用 Vuex 时,在属于 Vuex 的 state 上使用 v-model 会比较棘手:

<input v-model="obj.message">

假设这里的 obj 是在计算属性中返回的一个属于 Vuex store 的对象,在用户输入时,v-model 会试图直接修改obj.message。在严格模式中,因为这个修改不是在 mutation 函数中执行的, 这里会抛出一个错误

 

方法一:

用『Vuex 的思惟』去解决这个问题的方法是:给 <input> 中绑定 value,而后侦听 input 或者 change 事件,在事件回调中调用 action:

<input :value="message" @input="updateMessage">

computed: {

  ...mapState({ message: state => state.obj.message })

},

methods: { updateMessage (e) {

  this.$store.commit('updateMessage', e.target.value)

} }

 

下面是 mutation 函数:

mutations: {
  updateMessage (state, message) {
    state.obj.message = message
  }
}

 

方法二:

使用带有 setter 的双向绑定计算属性

<input v-model="message">

computed: {
  message: {
    get () {
      return this.$store.state.obj.message
    },
    set (value) {
      this.$store.commit('updateMessage', value)
    }
  }
}

 

 

API 参考

Vuex.Store 构造器选项

  • state

类型: Object

Vuex store 实例的根 state 对象

 

  • mutations

类型: { [type: string]: Function }

函数老是接受 state 做为第一个参数(若是定义在模块中,则为模块的局部状态),payload 做为第二个参数(可选)

 

  • actions

类型: { [type: string]: Function }

在 store 上注册 action。处理函数接受一个 context 对象,包含如下属性:

{
  state, // 等同于 store.state, 若在模块中则为局部状态
  rootState, // 等同于 store.state, 只存在于模块中
  commit, // 等同于 store.commit
  dispatch, // 等同于 store.dispatch
  getters // 等同于 store.getters
}

 

  • getters

类型: { [key: string]: Function }
在 store 上注册 getter,getter 方法接受如下参数:
  state, // 若是在模块中定义则为模块的局部状态
  getters, // 等同于 store.getters
  rootState // 等同于 store.state
注册的 getter 暴露为 store.getters。

 

  • modules

类型: Object
包含了子模块的对象,会被合并到 store,大概长这样:
{
  key: {
    state,
    mutations,
    actions?,
    getters?,
    modules?
  },
  ...
}
与根模块的选项同样,每一个模块也包含 state 和 mutations 选项。模块的状态使用 key 关联到 store 的根状态。模块的 mutation 和 getter 只会接收 module 的局部状态做为第一个参数,而不是根状态,而且模块 action 的 context.state 一样指向局部状态。

 

  • plugins

类型: Array<Function>
一个数组,包含应用在 store 上的插件方法。这些插件直接接收 store 做为惟一参数,能够监听 mutation(用于外部地数据持久化、记录或调试)或者提交 mutation (用于内部数据,例如 websocket 或 某些观察者)

 

 

Vuex.Store 实例属性

  • state

类型: Object
根状态,只读。

  • getters

类型: Object
暴露出注册的 getter,只读。

 

Vuex.Store 实例方法

  • commit(type: string, payload?: any) | commit(mutation: Object)

提交 mutation。 

 

  • dispatch(type: string, payload?: any) | dispatch(action: Object)

分发 action。返回 action 方法的返回值,若是多个处理函数被触发,那么返回一个 Pormise。 

 

  • replaceState(state: Object)

替换 store 的根状态,仅用状态合并或 time-travel 调试。

 

  • watch(getter: Function, cb: Function, options?: Object)

响应式地监测一个 getter 方法的返回值,当值改变时调用回调函数。getter 接收 store 的状态做为惟一参数。接收一个可选的对象参数表示 Vue 的 vm.$watch 方法的参数。

 

  • subscribe(handler: Function)

注册监听 store 的 mutation。handler 会在每一个 mutation 完成后调用,接收 mutation 和通过 mutation 后的状态做为参数:
store.subscribe((mutation, state) => {
  console.log(mutation.type)
  console.log(mutation.payload)
})
一般用于插件

 

  • registerModule(path: string | Array<string>, module: Module)

注册一个动态模块。 详细介绍

 

  • unregisterModule(path: string | Array<string>)

卸载一个动态模块。 详细介绍

相关文章
相关标签/搜索