Vuex 快速入门上手教程

一. 什么是Vuex?

vuex-explained-visually.png

Vuex是一个专门为Vue.js应用程序开发的状态管理模式, 它采用集中式存储管理所有组件的公共状态, 并以相应的规则保证状态以一种可预测的方式发生变化.

Vuex核心

上图中绿色虚线包裹起来的部分就是Vuex的核心, state中保存的就是公共状态, 改变state的唯一方式就是通过mutations进行更改. action 的作用跟mutation的作用是一致的,它提交mutation,从而改变state,是改变state的一个增强版.Action 可以包含任意异步操作。可能你现在看这张图有点不明白, 等经过本文的解释和案例演示, 再回来看这张图, 相信你会有更好的理解.

二. 为什么要使用Vuex?

试想这样的场景, 比如一个Vue的根实例下面有一个父组件名为App.vue, 它下面有两个子组件A.vueB.vue, App.vue想要与A.vue或者B.vue通讯可以通过props传值的方式。但是如果A或者B组件有子组件,并且要实现父组件与孙子组件的通信。或者与嵌套的更深的组件之间的通信就很麻烦。如下图:

716127-20180119171257271-1822439203.png

另外如果A.vueB.vue之间的通讯他们需要共有的父组件通过自定义事件进行实现,或者通过中央事件总线
实现。也很麻烦。如下图:

716127-20180119171307849-26505562.png

Vuex就是为了解决这一问题出现的

三.如何引入Vuex?

  1. 安装vuex:
npm install vuex --save
  1. main.js添加:
import Vuex from 'vuex'

Vue.use( Vuex );

const store = new Vuex.Store({
    //待添加
})

new Vue({
    el: '#app',
    store,
    render: h => h(App)
})

四. Vuex的核心概念?

为了方便理解概念,我做了一个vuex的demo。git地址:(vuex demo)[https://github.com/zhou111222/vue-.git]
vuex的文件在store文件夹下。store中的modules文件下包含两个文件。文件名和页面的名称是一致的,代表每个页面的vuex。index文件负责组合modules文件夹中各个页面的vuex。并导出。mutations-type文件里面定义一些操作mutation的字符串常量变量名,这里是定义一些动作名,所以名字一般是set 或者是update,然后再结合state.js中定义的变量对象,export多个常量。

image.png

核心概念1: State

state就是Vuex中的公共的状态, 我是将state看作是所有组件的data, 用于保存所有组件的公共数据.

  • 此时我们就可以把项目中的公共状态抽离出来, 放到mudules对应页面的state中,代码如下:
//detail.js
import * as types from '../mutation-type'

const state = { // 要设置的全局访问的state对象
  gold: 'BALLY/巴利',
  num: 1,
  groupData: {}
}

export default {
  namespaced: true, // 用于在全局引用此文件里的方法时标识这一个的文件名
  state
}

// home.js
import * as types from '../mutation-type'

const state = { // 要设置的全局访问的state对象
  carNumber: 0
}
export default {
  namespaced: true, // 用于在全局引用此文件里的方法时标识这一个的文件名
  state
}

  • 此刻store文件夹下的index代码。两个页面的store进行合并:
//ProductListOne.vue
import Vue from 'vue'
import Vuex from 'vuex'
import home from './modules/home'
import detail from './modules/details'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    home,
    detail
  }
})

在main.js中讲store注入到vue中。代码如下:

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
import VueBus from './assets/js/bus'
// 中央事件总线封装
Vue.use(VueBus)
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store, // 使用store
  components: { App },
  template: '<App/>'
})

home.vue和detai.vue中使用state的方式如下:

{{this.$store.state.属性名}}

核心概念2: Getters

可以将getter理解为store的computed属性, getters的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。

  • 此时,我们可以在store/modules/home.js中添加一个getters对象, 其中的carNum将依赖carNumber的值。
import * as types from '../mutation-type'

const state = { // 要设置的全局访问的state对象
  carNumber: 0
}

const getters = {
  carNum (state) {
    return state.carNumber
  }
}
export default {
  namespaced: true, // 用于在全局引用此文件里的方法时标识这一个的文件名
  state,
  getters
}

  • 另外,我们可以在store/modules/detail.js中添加一个getters对象, 其中的getProductdNum将依赖state.num的值。getGroupData 将依赖state.groupData的值。
//home.js
import * as types from '../mutation-type'

const state = { // 要设置的全局访问的state对象
  gold: 'BALLY/巴利',
  num: 1,
  groupData: {}
}

const getters = {
  getProductdNum (state) {
    return state.num
  },
  getGroupData (state) {
    return state.groupData
  }
}

export default {
  namespaced: true, // 用于在全局引用此文件里的方法时标识这一个的文件名
  state,
  getters
}

核心概念3: Mutations

我将mutaions理解为store中的methods, mutations对象中保存着更改数据的回调函数,函数第一个参数是state, 第二参数是payload, 也就是自定义的参数.该函数名的名称官方规定叫type,在模块化的思想中。type的名称被单独抽离出来放到了mutation-type文件。mutation-types.js:在这里面定义一些操作mutation的字符串常量变量名,这里是定义一些动作名,所以名字一般是set 或者是update,然后再结合state.js中定义的变量对象,export多个常量 :


//存储mutation的一些相关的名字,也就是一些字符串常量
//即使用常量替代mutation类型
//mutations里面定义一些方法,这里也就是定义mutations里面方法的名字
// 一些动作,所以用set,update

/* home页面 */
export const INIT_CAR_NUM = 'INIT_CAR_NUM'
export const ADD_CAR_NUM = 'ADD_CAR_NUM'
export const REDUCE_CAR_NUM = 'REDUCE_CAR_NUM'

/* detail页面 */
export const ADD_NUMBER = 'ADD_NUMBER'
export const GET_GROUP_DATA = 'GET_GROUP_DATA'
  • 下面,我们分别在store/modules/detail.js中添加mutations属性, mutations中的方法名(type)和在mutation-type.js中定义的名称一致。代码如下:
//home.js
import * as types from '../mutation-type'

const state = { // 要设置的全局访问的state对象
  carNumber: 0
}

const getters = {
  carNum (state) {
    return state.carNumber
  }
}

const mutations = {
  [types.INIT_CAR_NUM] (state, num) {
    state.carNumber = num
  },
  [types.ADD_CAR_NUM] (state) {
    state.carNumber = state.carNumber + 1
  },
  [types.REDUCE_CAR_NUM] (state) {
    if (state.carNumber > 0) {
      state.carNumber = state.carNumber - 1
    }
  }
}


export default {
  namespaced: true, // 用于在全局引用此文件里的方法时标识这一个的文件名
  state,
  getters,
  mutations
}

//detail.js
import * as types from '../mutation-type'

const state = { // 要设置的全局访问的state对象
  gold: 'BALLY/巴利',
  num: 1,
  groupData: {}
}

const getters = {
  getProductdNum (state) {
    return state.num
  },
  getGroupData (state) {
    return state.groupData
  }
}

const mutations = {
  [types.ADD_NUMBER] (state, sum) {
    state.num = state.num + sum
  },
  [types.GET_GROUP_DATA] (state, data) {
    state.groupData = Object.assign({}, state.groupData, data)
  }
}

export default {
  namespaced: true, // 用于在全局引用此文件里的方法时标识这一个的文件名
  state,
  getters,
  mutations
}
  • home.vue中添加2个按钮,为其绑定事件。一个按钮负责carNumber的加1,另一个减1。在methods中添加相应的方法。
//home.vue
<template>
  <div class="home">
    <div class="hello">
      <h1>{{ msg }}</h1>
      <ul>
        <li class="groupid">
          list页(vuex异步){{groupId? groupId : ''}}
        </li>
      </ul>
      <div class="car">购物车(vuex同步){{carNumber}}</div>
      <div class="control-car">
        <div class="reduce-car"
             @click="reduceCar()">-</div>
        <div class="add-car"
             @click="addCar()">+</div>
      </div>
      <button @click="goPage()">go list page</button>
      <con3></con3>
      <con4></con4>
    </div>
  </div>
</template>

<script>
import con3 from '@/components/con3'
import con4 from '@/components/con4'
import { mapState, mapMutations } from 'vuex'
import * as types from '@/store/mutation-type'

export default {
  name: 'Home',
  data () {
    return {
      msg: 'hello world'
    }
  },
  components: {
    con3,
    con4
  },
  beforeCreate: function () { },
  created: function () { },
  beforeMount: function () { },
  mounted: function () { },
  beforeUpdate: function () { },
  updated: function () { },
  beforeDestroy: function () { },
  destroyed: function () { },
  computed: {
    ...mapState({
      groupId: state => state.detail.groupData.groupId
    }),
    ...mapState({
      carNumber: state => state.home.carNumber
    })
  },
  methods: {
    goPage: function () {
      // this.$router.push({ path: '/detail' })
      this.$router.push({
        name: 'Detail',
        params: {
          page: '1', sku: '8989'
        }
      })
    },
    ...mapMutations({
      [types.ADD_CAR_NUM]: `home/${types.ADD_CAR_NUM}`,
      [types.REDUCE_CAR_NUM]: `home/${types.REDUCE_CAR_NUM}`
    }),
    addCar: function () {
      this[types.ADD_CAR_NUM]()
    },
    reduceCar: function () {
      this[types.REDUCE_CAR_NUM]()
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">
@import '../assets/style/reset.scss';
html,
body,
#app {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #fff;
}
#app {
  position: relative;
}
* {
  padding: 0;
  margin: 0;
}
.a {
  font-size: 40px;
}
.b {
  font-family: 'AlternateGothicEF-NoTwo';
  font-size: 40px;
}
h1,
h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
.groupid {
  width: 100%;
  height: 50px;
  background-color: #df8613;
  line-height: 50px;
  text-align: center;
  font-size: 26px;
  margin: 20px 0;
}
.car {
  width: 100%;
  height: 50px;
  background-color: #f5380a;
  line-height: 50px;
  text-align: center;
  font-size: 26px;
  margin: 20px 0;
}
.control-car {
  width: 100%;
  height: 70px;
  display: flex;
  justify-content: center;
  div {
    width: 60px;
    height: 60px;
    background-color: #42b983;
    float: left;
    margin-right: 20px;
    text-align: center;
    line-height: 60px;
    font-size: 26px;
    color: #fff;
    cursor: pointer;
  }
}
button {
  width: 100%;
  height: 50px;
  line-height: 50px;
  text-align: center;
  font-size: 26px;
  margin: 20px 0;
}
</style>

点击按钮,值会进行相应的增减。

  • 文件中有mapStates,mapMutations等函数,稍后讲。

核心概念4: Actions

actions 类似于 mutations,不同在于:

  • actions提交的是mutations而不是直接变更状态

  • actions中可以包含异步操作, mutations中绝对不允许出现异步

  • actions中的回调函数的第一个参数是context, 是一个与store实例具有相同属性和方法的对象

  • 此时,我们在detail.js中添加actions属性, 其中groupData采用接口异步操作获取数据,改变state中的groupData。

//details.js
import * as types from '../mutation-type'

const state = { // 要设置的全局访问的state对象
  gold: 'BALLY/巴利',
  num: 1,
  groupData: {}
}

const getters = {
  getProductdNum (state) {
    return state.num
  },
  getGroupData (state) {
    return state.groupData
  }
}

const mutations = {
  [types.ADD_NUMBER] (state, sum) {
    state.num = state.num + sum
  },
  [types.GET_GROUP_DATA] (state, data) {
    state.groupData = Object.assign({}, state.groupData, data)
  }
}

const actions = {
  getNewNum (context, num) {
    context.commit(types.ADD_NUMBER, num)
  },
  groupData (context, data) {
    context.commit(types.GET_GROUP_DATA, data)
  }
}

export default {
  namespaced: true, // 用于在全局引用此文件里的方法时标识这一个的文件名
  state,
  getters,
  mutations,
  actions
}

  • details.vue中的con1组件中添加一个按钮,为其添加一个点击事件, 给点击事件触发groupData方法
<template>
  <div class="con1">
    {{name}}
    <div class="groupid"
         @click="onLoad">
      list页获取异步接口数据{{user.groupId}}
    </div>
    <con2 v-bind="$attrs"
          v-on="$listeners"></con2>
    <div class="list1"></div>
  </div>
</template>

<script>
import con2 from './con2'
import { getGroupId } from '@/api/service'
import { mapActions } from 'vuex'

export default {
  data () {
    return {
      msg: 'con1',
      user: {}
    }
  },
  inheritAttrs: false,
  props: ['name'],
  components: {
    con2
  },
  mounted () { },
  methods: {
    ...mapActions({
      groupData: 'detail/groupData'
    }),
    onLoad () {
      getGroupId({
        appSource: 'secoo',
        sku: 52606943,
        source: 1,
        upk: '18210001657400782F74E3AB7FD929AED59F0415135D5665089292C437542835ED117B6D94EBB9CC36B4A5D49D3504B36E3795727824DF877ED0633F6DCDF88DA0D3355E9ACD2A0B2F892115DF6D2755F3297F5E93659937491D26B687A507A85A74C272F7C69FB28536BD6B31EDC482F8B979377EA3A749C8BC'
      }).then(res => {
        this.user = Object.assign({}, this.user, res)
        this.groupData(res)
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
@import '../assets/style/reset.scss';
html,
body,
#app {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #fff;
}
#app {
  position: relative;
}
* {
  padding: 0;
  margin: 0;
}
.a {
  font-size: 40px;
}
.b {
  font-family: 'AlternateGothicEF-NoTwo';
  font-size: 40px;
}
h1,
h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
button {
  width: 220px;
  height: 50px;
  line-height: 50px;
  text-align: center;
  font-size: 26px;
}
.groupid {
  width: 100%;
  height: 50px;
  background-color: #df8613;
  line-height: 50px;
  text-align: center;
  font-size: 26px;
  margin: 20px 0;
}
.list1 {
  width: 746px;
  height: 250px;
  background-color: red;
  border: 2px solid #000;
}
</style>


  • 点击按钮即可发现加载异步数据

核心概念5: Modules

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割

const home = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

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

const store = new Vuex.Store({
  modules: {
    home,
    detail
  }
})

store.state.home// -> home页面 的状态
store.state.detail // -> detail页面 的状态

改变state的时候使用mutation或者action中的方法也需要做一些修改:

//原来的
this.$store.commit('getGroupData');
this.$store.dispatch('etNewNum',5);
//修改后的
this.$store.commit('detail/getGroupData');
this.$store.dispatch('detail/getNewNum',5);

讲完这些基本概念之后再将一下这些属性的辅助函数:mapState, mapGetters, mapActions, mapMutations。

map映射函数

map映射函数 映射结果
mapState 将state映射到computed
mapActions 将actions映射到methods
mapGetters 将getters映射到computed

个人感觉,这些函数其实就是对state,gettters,mutations,actions的重命名而已。可以让你在写代码的时候少敲几个字母。在没有这些函数的时候。页面或者组件里使用state和getter需要this.store.state.num还有this.store.getter.num.如果页面有很多个地方使用了state和getter会很麻烦。使用这些辅助函数可以解决这些问题。

使用时首先引入:

import { mapState, mapActions, mapGetters, mapMutations } from 'vuex'
mapState:

他是对state的对象进行二次计算,他可以简化我们代码,这样我们获取a,不用写this.$store.state.a一大串了,尤其对于我们组件中用到次数挺多的情况下,我们完全可以用mapState来代替。
-需要在computed中使用mapState

computed: {
  ...mapState(['a', 'b']),
}

就可以代替这段代码:

computed: {
  a() {
    return this.$store.state.a
  },
  b() {
    return this.$store.state.b
  },
}

注意,如果a和b不是同一个文件下的属性,j假如a属于detail.b属于home.可以这么写:

computed: {
  ...mapState({
    a: state => state.detail.a
  }),
...mapState({
    a: state => state.home.b
  }),
}

使用方法:

this.a

官方的使用方法如下:


img_ccc7f93b277d85a17130b533a4090e8e.png
mapGetters

我们可以理解成他是和mapState一样,都是对state里面的参数进行计算,并返回相应的值,所以我们平常看到的mapState.mapGetters都是在computed属性里面,但是和mapState有点不同的是,mapState是仅对state里面的参数进行计算并返回,而mapGetters是对state参数派生出的属性进行计算缓存

在computed中添加count的映射:

computed: {
  ...mapGetters(['count'])
}

等价于:

computed: {
  count() {
    return this.$store.getters.count
  }
}

使用方法:

this.count
mapMutations

mapMutations是写在methods里面,因为他触发的是方法
在methods中添加映射

methods: {
 ...mapMutations({
      [types.ADD_CAR_NUM]: `home/${types.ADD_CAR_NUM}`,
      [types.REDUCE_CAR_NUM]: `home/${types.REDUCE_CAR_NUM}`
    }),
},

等价于:

methods: {
    this.$store.commit(`home/${types.ADD_CAR_NUM}`, n)
    this.$store.commit(`home/${types.REDUCE_CAR_NUM}`, n)
}

使用方法:

this[types.ADD_CAR_NUM]()
this[types.REDUCE_CAR_NUM]()
mapActions

mapAcions是写在methods里面,因为他触发的是方法
在methods中添加addA和addB的映射

methods: {
  ...mapActions({
    groupData: 'detail/groupData'
  }),
},

等价于:

methods: {
  addA(n) {
    this.$store.dispatch('detail/groupData', n)
  }
}

'groupData'是定义的一个函数别名称,挂载在到this(vue)实例上,

注意:'detail/groupData' 才是details页面actions里面函数方法名称 。

调用的方法:

this.groupData(res)

至此,vuex中的常用的一些知识点使用算是简单的分享完了,当然了,相信这些只是一些皮毛!只能说是给予刚接触vuex的初学者一个参考与了解吧!有哪里不明白的或不对的,留言下,咱们可以一起讨论、共同学习!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容

  • 安装 npm npm install vuex --save 在一个模块化的打包系统中,您必须显式地通过Vue.u...
    萧玄辞阅读 2,920评论 0 7
  • ### store 1. Vue 组件中获得 Vuex 状态 ```js //方式一 全局引入单例类 // 创建一...
    芸豆_6a86阅读 721评论 0 3
  • Vuex是什么? Vuex 是一个专为 Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件...
    萧玄辞阅读 3,091评论 0 6
  • vuex 场景重现:一个用户在注册页面注册了手机号码,跳转到登录页面也想拿到这个手机号码,你可以通过vue的组件化...
    sunny519111阅读 7,999评论 4 111
  • ### store 1. Vue 组件中获得 Vuex 状态 ```js //方式一 全局引入单例类 // 创建一...
    芸豆_6a86阅读 337评论 0 0