博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
(生产)vuex - 状态管理
阅读量:7013 次
发布时间:2019-06-28

本文共 13328 字,大约阅读时间需要 44 分钟。

参考: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>

 

  • NPM

 

npm install vuex --save

 

 

State

单一状态树

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

使用

    store.js

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
})

 

main.js

   import store from './store'

new Vue({

  el: '#app',
  store,
  ...............
})

    // store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store访问到

 

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。当我们在之后介绍到 时,你就知道 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>)

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

 

 

转载于:https://www.cnblogs.com/vs1435/p/7018550.html

你可能感兴趣的文章