# vuex

数据管理中心,组件共享数据

# 简述vuex怎么流程

1 先配置
state {
    存放动态数据的,要提前声明
}
mutations {
    同步 修改数据
}
getters {
    计算 state中的数据
}
actions{
    异步操作,之后再去 提交mutations
}
2 页面 去使用
store.state.xxx
store.commit('xxx')
store.getter.xxx
store.dispatch('xxx')

3 帮助方法
mapState
mapGetters
mapMutations
mapActions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

简单实践

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count:1
  },
  mutations: { //改变数据源
    increase(state){  //形参 state
      state.count += 1
    }
  },
  //计算属性,里面的值都是函数
  // 对 state的数据进行加工

  getters: {
    money: state => {
      return state.count + '元'
    }
  },
  actions: { // 异步 操作时 使用
    //Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象
    // increaseAsync(context){} ,payLoad 载荷
    increaseAsync( {state , commit},payLoad ){
      setTimeout( ()=> {
       commit('increase')
      },1500)
    }
  },
  modules: {
  }
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<template>
  <div>
    <router-view></router-view>
    <h1>store: {{count}}</h1>
    <button @click="inc">增加1</button>
    <h1>getters: {{money}}</h1>
    <button @click="incAsync">异步 的增加1</button>
  </div>
</template>
<script>
import { mapState,mapGetters,mapMutations,mapActions } from "vuex";
export default {
  computed: {
    // 帮助方法返回一个对象
    // 相当于:{count: this.$store.state.count}
    //将其拓客 ,取出count属性
    ...mapState(['count']),
    ...mapGetters(['money'])
  },
  methods: {
    // 相当于 key : value ,value为一个函数
    // increase: function(){ this.$store.commit("increase");}
    ...mapMutations(['increase']),
    // increaseAsync: function(){ this.$store.dispatch("increaseAsync");}
    ...mapActions(['increaseAsync']),
    inc() {
      //提交方法
      // this.$store.commit("increase");
      this.increase()
    },
    incAsync() {
      //异步派发
      // this.$store.dispatch("increaseAsync");
      this.increaseAsync()
    }
  }
};
</script>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39