Vuex 状态管理

291 阅读8分钟

概述

  • 组件通信方式回顾
  • Vuex 核心概念和基本使用回顾
  • 购物车案例
  • 模拟实现 Vuex

组件内的状态管理流程

Vue 最核心的两个功能: 数据驱动和组件化

组件化开发给我们带来了:

  • 更快的开发效率
  • 更好的可维护性

每个组件都有自己的状态、视图和行为等组成部分。

new Vue({
  // state
  data () {
    return {
      count: 0
    } 
  },
  // view
  template: `
    <div>{{ count }}</div>
  `,
  // actions 
  methods: {
     increment () { 
       this.count++
     } 
  }
})

状态管理包含以下几部分:

  • state,驱动应用的数据源;
  • view,以声明方式将 state 映射到视图;
  • actions,响应在 view 上的用户输入导致的状态变化。

此处的箭头是数据的流向,此处的数据流向是单向的。 多个组件共享数据的时候会破坏这种简单的结构。

组件间通信方式

大多数场景下的组件都并不是独立存在的,而是相互协作共同构成了一个复杂的业务功能。在 Vue 中为 不同的组件关系提供了不同的通信规则

三种组件间通信方式

  • 父组件给子组件传值
  • 子组件给父组件传值
  • 不相关组件之间传值

父组件给子组件传值

  • 子组件中通过props接收数据
  • 父组件中通过相应属性给子组件传值 01-Child.vue
<template>
  <div>
    <h1>Props Down Child</h1>
    <h2>{{ title }}</h2>
  </div>
</template>

<script>
export default {
  // props: ['title'],
  // 对象形式可约定传值类型
  props: {
    title: String
  }
}
</script>

<style>

</style>

01-Parent.vue

<template>
  <div>
    <h1>Props Down Parent</h1>
    <child title="My journey with Vue"></child>
  </div>
</template>

<script>
import child from './01-Child'
export default {
  components: {
    child
  }
}
</script>

<style>

</style>

子组件给父组件传值

在子组件中使用 $emit 发布一个自定义事件

02-Child.vue

<template>
  <div>
    <h1 :style="{ fontSize: fontSize + 'em' }">Props Down Child</h1>
    <button @click="handler">文字增大</button>
  </div>
</template>

<script>
export default {
  props: {
    fontSize: Number
  },
  methods: {
    handler () {
      this.$emit('enlargeText', 0.1)
    }
  }
}
</script>

<style>

</style>

02-Parent.vue

<template>
  <div>
    <h1 :style="{ fontSize: hFontSize + 'em'}">Event Up Parent</h1>

    这里的文字不需要变化

    <child :fontSize="hFontSize" v-on:enlargeText="enlargeText"></child>
    <child :fontSize="hFontSize" v-on:enlargeText="enlargeText"></child>
    <child :fontSize="hFontSize" v-on:enlargeText="hFontSize += $event"></child>
  </div>
</template>

<script>
import child from './02-Child'
export default {
  components: {
    child
  },
  data () {
    return {
      hFontSize: 1
    }
  },
  methods: {
    enlargeText (size) {
      this.hFontSize += size
    }
  }
}
</script>

<style>

</style>

行内可以通过 $event 来获取事件传递的参数,在事件处理函数中是不能这么使用的。

不相关组件之间传值

不相关组件的通信也是通过自定义事件的方式,但是由于不是父子组件关系,所以不能通过触发事件传值。所以需要使用eventBus创建一个公共的Vue实例,这个实例的作用是作为事件总线或者事件中心。

eventbus.js

import Vue from 'vue'
export default new Vue()

03-Sibling-01.vue

<template>
  <div>
    <h1>Event Bus Sibling01</h1>
    <div class="number" @click="sub">-</div>
    <input type="text" style="width: 30px; text-align: center" :value="value">
    <div class="number" @click="add">+</div>
  </div>
</template>

<script>
import bus from './eventbus'

export default {
  props: {
    num: Number
  },
  created () {
    this.value = this.num
  },
  data () {
    return {
      value: -1
    }
  },
  methods: {
    sub () {
      if (this.value > 1) {
        this.value--
        bus.$emit('numchange', this.value)
      }
    },
    add () {
      this.value++
      bus.$emit('numchange', this.value)
    }
  }
}
</script>

<style>
.number {
  display: inline-block;
  cursor: pointer;
  width: 20px;
  text-align: center;
}
</style>

03-Sibling-02.vue

<template>
  <div>
    <h1>Event Bus Sibling02</h1>

    <div>{{ msg }}</div>
  </div>
</template>

<script>
import bus from './eventbus'
export default {
  data () {
    return {
      msg: ''
    }
  },
  created () {
    bus.$on('numchange', (value) => {
      this.msg = `您选择了${value}件商品`
    })
  }
}
</script>

<style>

</style>

通过 ref 获取子组件

其他常见方式

  • $root
  • $parent
  • $children
  • $refs 可以通过这些相关的属性,来获取父子组件、根组件对象上的成员实现组件之间的通信,但是这些都是不被推荐的实现方式,只有在项目非常小,或者在开发自定义组件的时候才会使用到。如果是大型项目还是推荐vuex来管理状态。

ref 有两个作用:

  • 如果你把它作用到普通 HTML 标签上,则获取到的是 DOM
  • 如果你把它作用到组件标签上,则获取到的是组件实例

04-Child.vue

<template>
  <div>
    <h1>ref Child</h1>
    <input ref="input" type="text" v-model="value">
  </div>
</template>

<script>
export default {
  data () {
    return {
      value: ''
    }
  },
  methods: {
    focus () {
      this.$refs.input.focus()
    }
  }
}
</script>

<style>

</style>

04-Parent.vue

在父组件等渲染完毕后使用 $refs 访问:

<template>
  <div>
    <h1>ref Parent</h1>

    <child ref="c"></child>
  </div>
</template>

<script>
import child from './04-Child'
export default {
  components: {
    child
  },
  mounted () {
    this.$refs.c.focus()
    this.$refs.c.value = 'hello input'
  }
}
</script>

<style>

</style>

$refs 只会在组件渲染完成之后生效,并且它们不是响应式的。这仅作为一个用于直接操作子组件的“逃生舱”——你应该避免在模板或计算属性中访问 $refs 。如果滥用这种方式会导致数据管理混乱。

简易的状态管理方案

如果多个组件之间要共享状态(数据),使用上面的方式虽然可以实现,但是比较麻烦,而且多个组件之 间互相传值很难跟踪数据的变化,如果出现问题很难定位问题。

当遇到多个组件需要共享状态的时候,典型的场景:购物车。我们如果使用上述的方案都不合适,我们会遇到以下的问题

  • 多个视图依赖于同一状态。
  • 来自不同视图的行为需要变更同一状态。

对于问题一,传参的方法对于多层嵌套的组件将会非常繁琐,并且对于兄弟组件间的状态传递无能为力。

对于问题二,我们经常会采用父子组件直接引用或者通过事件来变更和同步状态的多份拷贝。以上的这些模式非常脆弱,通常会导致无法维护的代码。

因此,我们为什么不把组件的共享状态抽取出来,以一个全局单例模式管理呢?在这种模式下,我们的组件树构成了一个巨大的“视图”,不管在树的哪个位置,任何组件都能获取状态或者触发行为!

我们可以把多个组件的状态,或者整个程序的状态放到一个集中的位置存储,并且可以检测到数据的更改。你可能已经想到了 Vuex。

这里我们先以一种简单的方式来实现

  • 首先创建一个共享的仓库 store 对象 store.js
export default {
  debug: true,
  state: {
    user: {
      name: 'xiaomao', age: 18,
      sex: '男'
    } 
  },
  setUserNameAction (name) { 
    if (this.debug) {
      console.log('setUserNameAction triggered:', name) 
    }
    this.state.user.name = name 
  }
}
  • 把共享的仓库 store 对象,存储到需要共享状态的组件的 data 中

05-componentA.vue

<template>
  <div>
    <h1>componentA</h1>
    user name: {{ sharedState.user.name }}
    <button @click="change">Change Info</button>
  </div>
</template>

<script>
import store from './store'
export default {
  methods: {
    change () {
      store.setUserNameAction('componentA')
    }
  },
  data () {
    return {
      privateState: {},
      sharedState: store.state
    }
  }
}
</script>

<style>

</style>

05-componentB.vue

<template>
  <div>
    <h1>componentB</h1>
    user name: {{ sharedState.user.name }}
    <button @click="change">Change Info</button>
  </div>
</template>

<script>
import store from './store'
export default {
  methods: {
    change () {
      store.setUserNameAction('componentB')
    }
  },
  data () {
    return {
      privateState: {},
      sharedState: store.state
    }
  }
}
</script>

<style>

</style>

接着我们继续延伸约定,组件不允许直接变更属于 store 对象的 state,而应执行 action 来分发 (dispatch) 事件通知 store 去改变,这样最终的样子跟 Vuex 的结构就类似了。这样约定的好处是,我们能够记录所有 store 中发生的 state 变更,同时实现能做到记录变更、保存状态快照、历史回滚/时光旅行的先进的调试工具

Vuex

什么是 Vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 devtools extension,提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调 试功能。

  • Vuex 是专门为 Vue.js 设计的状态管理库
  • 它采用集中式的方式存储需要共享的数据
  • 从使用角度,它就是一个 JavaScript 库
  • 它的作用是进行状态管理,解决复杂组件通信,数据共享

什么情况下使用 Vuex

官方文档:

Vuex 可以帮助我们管理共享状态,并附带了更多的概念和框架。这需要对短期和长期效益进行权衡。

如果您不打算开发大型单页应用,使用 Vuex 可能是繁琐冗余的。确实是如此——如果您的应用 够简单,您最好不要使用 Vuex。一个简单的 store 模式就足够您所需了。但是,如果您需要构建 一个中大型单页应用,您很可能会考虑如何更好地在组件外部管理状态,Vuex 将会成为自然而然的选择。引用 Redux 的作者 Dan Abramov 的话说就是:Flux 架构就像眼镜:您自会知道什么时候需要它。

当你的应用中具有以下需求场景的时候:

  • 多个视图依赖于同一状态
  • 来自不同视图的行为需要变更同一状态 建议符合这种场景的业务使用 Vuex 来进行数据管理,例如非常典型的场景:购物车。

注意:Vuex 不要滥用,不符合以上需求的业务不要使用,反而会让你的应用变得更麻烦。

核心概念

  • Store 使用 Vuex 的核心。每一个应用仅有一个Store,Store是一个容器,包含着应用的大部分状态,我们不能直接更改,而是通过mutation改变Store中的状态。
  • State 状态。保存在Store中,因为Store是唯一的,所以状态也是唯一的,称为状态单一树,但是所有的状态都保存在State中的话会让程序难以维护,可以通过后续的模块解决该问题。注意这里的状态是响应式的。
  • Getter Getter就像是Vuex中的计算属性,方便从其他属性派生出其他的值,它内部可以对计算结果进行缓存,只有当依赖的状态发生改变的时候才会重新计算。
  • Mutation 状态的变化必须要通过提交mutation来完成。
  • Action 与Mutation类似,不同的是Action可以进行异步的操作,内部改变状态的时候都需要提交Mutation。
  • Module 由于使用单一状态树,应用的所有状态会集中到比较大的对象上,当应用比较复杂时,Store对象就会变得臃肿,为了解决以上问题,Vuex允许我们将Store分割成模块,每个模块又有自己的State、Mutation、Action等,甚至是嵌套的子模块。

基本代码结构

  • 导入 Vuex
  • 注册 Vuex
  • 注入 $store 到 Vue 实例 store.js
import Vue from 'vue'
import Vuex from 'vuex'
import products from './modules/products'
import cart from './modules/cart'

Vue.use(Vuex)

export default new Vuex({
  state: {
    count: 0,
    msg: 'Hello Vuex'
  },
  getters: {
    reverseMsg (state) {
      return state.msg.split('').reverse().join('')
    }
  },
  mutations: {
    increate (state, payload) {
      state.count += payload
    }
  },
  actions: {
    increateAsync (context, payload) {
      setTimeout(() => {
        context.commit('increate', payload)
      }, 2000)
    }
  },
  modules: {
    products,
    cart
  }
})

main.js

import store from './store'

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

State

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

State是响应式的,获取数据时直接从State中获取。例如$store.state.count

使用 mapState 简化 State 在视图中的使用,mapState 返回计算属性

mapState 有两种使用的方式:

  • 接收数组参数
// 该方法是 vuex 提供的,所以使用前要先导入 
import { mapState } from 'vuex'
// mapState 返回名称为 count 和 msg 的计算属性 
// 在模板中直接使用 count 和 msg
computed: {
  // count: state => state.count
  ...mapState(['count', 'msg']), 
}
  • 接收对象参数 如果当前视图中已经有了 count 和 msg,如果使用上述方式的话会有命名冲突,解决的方式:
// 该方法是 vuex 提供的,所以使用前要先导入 
import { mapState } from 'vuex'
// 通过传入对象,可以重命名返回的计算属性
// 在模板中直接使用 num 和 message 
computed: {
  // ...mapState({
  // num: state => state.count, 
  //  message: state => state.msg
  // }) 
  ...mapState({
    num: 'count',
    message: 'msg'
  })
}

Getter

Getter 就是 store 中的计算属性(对State中属性做简单的处理),

可通过 $store.getters.reverseMsg访问使用

使用 mapGetter 简化视图中的使用

import { mapGetter } from 'vuex'

computed: { 
  ...mapGetter(['reverseMsg']), 
  // 改名,在模板中使用 reverse 
  ...mapGetter({
    reverse: 'reverseMsg'
  })

Mutation

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

使用 Mutation 改变状态的好处是,集中的一个位置对状态修改,不管在什么地方修改,都可以追踪到状态的修改。可以实现高级的 time-travel 调试功能。

可通过 $store.commit('increate', 10)访问使用

使用 mapMutations 简化视图中的使用

import { mapMutations } from 'vuex'

methods: {
  ...mapMutations(['increate']), 
  // 传对象解决重名的问题 
  ...mapMutations({
      increateMut: 'increate'
  })
}

然后可以在视图中通过 increate(10) 直接使用

Action

Action 类似于 mutation,不同在于:

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

可通过 $store.dispatch('increateAsync', 10)访问使用

使用 mapMutations 简化视图中的使用

import { mapActions } from 'vuex'

methods: { 
  ...mapActions(['increateAsync']), 
  // 传对象解决重名的问题 
  ...mapActions({
      increateAction: 'increateAsync'
    })
}

Module

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

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

模块内的state可以通过 $store.state.moduleName.moduleState访问

此时打印Store对象,发现_mutations中有increate和setProducts,通过在module中开启命名空间namespaced: true,此时_mutations中是increate和products/setProducts。

使用:

computed: {
  ...mapState('products', ['products'])
},
methods: {
  ...mapMutations('products', ['setProducts'])
}

这样可直观看出是从哪个模块获取的。

Vuex 严格模式

通过mutation来更改state这只是一个约定,如果非要直接更改state也不会有什么语法错误,开启严格模式后如果直接在组件中修改state会抛出错误。

需要强调的是不要在生产环境下开启严格模式,因为严格模式会深度检查状态树来检查不合规的状态改变会影响性能。可以在开发模式下启用在生产环境下关闭。

export default new Vuex.Store({
  strict: process.env.NODE_ENV !== 'production'
  ...
}

Vuex 插件

可在每次提交完mutation后做一些事情,例如打印日志,本地存储数据

const myPlugin = store => {
  store.subscribe((mutation, state) => {
    if (mutation.type.startsWith('cart/')) {
      window.localStorage.setItem('cart-products', JSON.stringify(state.cart.cartProducts))
    }
  })
}

export default new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
    products,
    cart
  },
  plugins: [myPlugin]
})

购物车案例

效果

代码

Vuex 模拟实现

回顾基础示例,模拟实现一个 Vuex 实现同样的功能

import Vue from 'vue'
import Vuex from 'vuex' 
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    count: 0,
    msg: 'Hello World'
  }, 
  getters: {
    reverseMsg (state) {
      return state.msg.split('').reverse().join('')
    } 
  },
  mutations: {
    increate (state, payload) {
      state.count += payload.num 
    }
  }, 
  actions: {
    increate (context, payload) {
      setTimeout(() => {
          context.commit('increate', { num: 5    }) 
      }, 2000)
    } 
  }
})

实现思路

  • 实现 install 方法
    • Vuex 是 Vue 的一个插件,所以和模拟 VueRouter 类似,先实现 Vue 插件约定的 install 方法
  • 实现 Store 类
    • 实现构造函数,接收 options
    • state 的响应化处理
    • getter 的实现
    • commit、dispatch 方法

install 方法

let _Vue = null
function install (Vue) {
  _Vue = Vue _Vue.mixin({
    beforeCreate () {
      if (this.$options.store) {
        Vue.prototype.$store = this.$options.store 
      }
    } 
  })
}

Store 类

class Store {
  constructor (options) {
    const {
      state = {},
      getters = {},
      mutations = {},
      actions = {}
    } = options
    this.state = _Vue.observable(state)
    // 此处不直接 this.getters = getters,是因为下面的代码中要方法 getters 中的 key
    // 如果这么写的话,会导致 this.getters 和 getters 指向同一个对象
    // 当访问 getters 的 key 的时候,实际上就是访问 this.getters 的 key 会触发 key 属性 的 getter
    // 会产生死递归
    this.getters = Object.create(null)
    Object.keys(getters).forEach(key => {   
      Object.defineProperty(this.getters, key, {
        get: () => getters[key](this.state)  
      })
    })
    this.mutations = mutations 
    this.actions = actions
  }
  commit (type, payload) {  
    this.mutations[type](this.state, payload)
  }
  dispatch (type, payload) { 
    this.actions[type](this, payload)
  } 
}
// 导出模块 
export default {
  Store,
  install
}

使用自己实现的 Vuex

src/store/index.js 中修改导入 Vuex 的路径,测试

import Vuex from '../myvuex' // 注册插件
Vue.use(Vuex)