Vue 之状态管理 vuex 学习
2018-03-07 16:24
387 查看
Vuex 介绍
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。
它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
举一个很常见的例子:子组件调用父组件一般通过event 来完成,比如
this.$emit()…一旦业务复杂,组件越来越多,调用关系越来越复杂的时候,我们可以用Vuex 来
集中管理这些组件的变化
一.状态管理模式
new Vue({ // state data () { return { count: 0 } }, // view template: `<div>{{ count }}</div>`, // actions methods: { increment () { this.count++ } } })
这个状态自管理应用包含以下几个部分:
state,驱动应用的数据源;
view,以声明方式将 state 映射到视图;
actions,响应在 view 上的用户输入导致的状态变化。
二.最简单的store
创建一个简单的store示例:// 如果在模块化构建系统中,请确保在开头调用了 Vue.use(Vuex) const store = new Vuex.Store({ state: {count: 0}, mutations: { increment (state) { state.count++ } } })
获取状态对象:
store.state
触发状态更新:
store.commit('increment')
我们通过
store.commit('increment')提交到
mutations来改变
count的值
三.Store (单一状态树)
Vuex 使用单一状态树——是的,用一个对象就包含了全部的应用层级状态。至此它便作为一个“唯一数据源 (SSOT)”而存在。这也意味着,每个应用将仅仅包含一个 store 实例
在Vue组件中展示状态
最简单的办法是使用计算属性:// 创建一个 Counter 组件 const Counter = { template: `<div>{{ count }}</div>`, computed: { count () { return store.state.count } } }
每当
store.state.count变化的时候, 都会重新求取计算属性,并且触发更新相关联的 DOM。
Vuex 通过 store 选项,提供了一种机制将状态从根组件“注入”到每一个子组件中(需调用
Vue.use(Vuex)):
const app = new Vue({ el: '#app', // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件 store, components: { Counter }, template: ` <div class="app"> <counter></counter> </div> ` }) //通过在根实例中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中 //count 可以通过 this.$store 来访问到 const Counter = { template: `<div>{{ count }}</div>`, computed: { count () { return this.$store.state.count } } }
mapState 辅助函数
当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性
// 在单独构建的版本中辅助函数为 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' ])
mapState 与局部计算属性混合使用
computed: { localComputed () { /* ... */ }, // 使用对象展开运算符将此对象混入到外部对象中 ...mapState({ // ... }) }
四.Getter
Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
const store = new Vuex.Store({ state: { todos: [ { id: 1, text: '...', done: tru e1fd e }, { 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
也可以通过让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用。
getters: { // ... getTodoById: (state) => (id) => { return state.todos.find(todo => todo.id === id) } } store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
mapGetters 辅助函数
import { mapGetters } from 'vuex' export default { // ... computed: { // 使用对象展开运算符将 getter 混入 computed 对象中 ...mapGetters([ 'doneTodosCount', 'anotherGetter', // ... ]) } }
如果你想将一个 getter 属性另取一个名字,使用对象形式
mapGetters({ // 映射 `this.doneCount` 为 `store.getters.doneTodosCount` doneCount: 'doneTodosCount' })
五.Mutation
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation,mutation 可以简单理解成更改 store 的控制器
每个 mutation 都有一个字符串的
事件类型 (type)和 一个
回调函数 (handler)。
这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:
const store = new Vuex.Store({ state: { count: 1}, mutations:{ increment : state = >{ // 变更状态 state.count++ } //提交载荷(Payload) incrementpara : (state,payload) = >{ state.count += payload.amount } } })
需要通过:
1.
store.commit('increment')来 调用 increment
2.
store.commit('incrementpara',{amount : 10})来 调用 incrementpara
对象风格的提交方式(handler 不变)
store.commit({ type: 'increment', amount: 10 })
注意事项
最好提前在你的 store 中初始化好所有所需属性。当需要在对象上添加新属性时,你应该
使用
Vue.set(obj, 'newProp', 123),
或者以新对象替换老对象。例如,利用 stage-3 的对象展开运算符我们可以这样写:
state.obj = { ...state.obj, newProp: 123 }
Mutation 必须是同步函数
在组件中提交 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')` }) } }
六.Action
所有的Mutation 都是同步方法,如果变更多个组件的状态,我们无法知道哪一个组件先回调,这时候就引入了ActionAction 类似于 mutation,不同在于:
Actio 提交的是 mutation,而不是直接变更状态。
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。
分发 Action
store.dispatch('increment')
为什么不直接分发mutation? mutation 受同步限制
actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }
// 以载荷形式分发 store.dispatch('incrementAsync', { amount: 10 }) // 以对象形式分发 store.dispatch({ type: 'incrementAsync', amount: 10 })
在组件中分发 Action
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')` }) } }
七.Module
当Store比较复杂的时候,vue把Store分割成moduleconst 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 的状态
模块动态注册
// 注册模块 `myModule` store.registerModule('myModule', { // ... }) // 注册嵌套模块 `nested/myModule` store.registerModule(['nested', 'myModule'], { // ... })
相关文章推荐
- asp.net状态管理学习二:session
- 简述vue状态管理模式之vuex
- ASP.NET学习笔记三 : 系统对象与状态管理(二)
- vue从入门到进阶:Vuex状态管理(十)
- ASP.NET温故而知新学习系列之ASP.NET中的状态—基于服务器端的状态管理Session(二)
- AngularJS—学习 ui-router - 管理状态
- 理解vuex -- vue的状态管理模式
- vue.js的状态管理vuex中store的使用
- Vue + Element UI 实现权限管理系统 前端篇(八):管理应用状态
- (生产)vuex - 状态管理
- 理解vuex的状态管理模式架构
- Vue 状态管理 Vuex
- HttpClient学习研究---第三章:http状态管理
- Web Service学习笔记:状态管理
- hdfs haadmin使用,DataNode动态上下线,NameNode状态切换管理,数据块的balance,HA下hdfs-api变化(来自学习资料)
- 简单实用vue状态管理vuex
- vue学习第13天,状态过渡
- Vue.js状态管理工具Vuex快速上手
- vuex 状态管理模式
- vue状态管理vue-vux使用