# Vuex重点笔记

# 1.是什么

vuex是用于组件间数据共享的一个vue插件,核心为vuex.store

# 2.如何配置

# 2.1创建vuex模块store/index.js

// 配置过程和router类似

// index.js
import Vue from 'vue'
import Vuex from 'vuex'
// 全局注册vuex插件
Vue.use(Vuex)
// 默认导出stroe
export default new Vuex.Store({
  state: {
    count: 0
  },
  // 只有mutation有资格修改state中的数据
  mutations: {
    add (state) {
      state.count += 1
      // mutations中不能进行异步操作
    }
  },
  // 专门进行异步操作的属性
  actions: {
      函数名(store){
          // 调用store.commit触发mutations中的方法
          setTimeout(store=>{
              store.commit("操作名",参数);
          })
      }
  },
  modules: {
      // 可以按模块配置不同的数据
  },
  // 可以对state中的数据进行包装,但不会修改数据
  getters: {
    packCount: function (state) {
      return '[getters]现在最新的count值是:' + state.count
    }
  }
})

# 2.2挂载到main.js中的vue实例

// 在main.js中挂载到vue实例
// main.js
import store from './store/index.js'

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

# 3.核心内容

# 3.1 state:共享数据

state: {
    count: 0
  }
# 使用方式一
{{this.$store.state.count}}
# 使用方式二
// 需要使用数据的组件.vue

// 1.按需导入mapState
import {mapState} from 'vuex'

// 2.利用扩展运算符设置为计算属性
computed:{
    ...mapState(['count'])
}

// 3.在template中直接使用
<p>{{count}} </p>

# 3.2 getters:包装数据

 // 可以对state中的数据进行包装,但不会修改数据
  getters: {
    packCount: function (state) {
      return '[getters]现在最新的count值是:' + state.count
    }
  }
# 使用方式一
<h3>{{this.$store.getters.packCount}}</h3>
# 使用方式二
// 需要使用数据的组件.vue

// 导入mapState
import { mapGetters } from 'vuex'

// 设置为计算属性
computed: {
    ...mapGetters(['packCount'])
}

// 3.在template中直接使用
<h3>{{packCount}}--扩展表达式</h3>

# 3.3 mutations:操作数据

 // 只有mutations有资格修改state中的数据
  mutations: {
    add (state) {
      state.count += 1
      // mutations中不能进行异步操作
    },
    //传参
    addNum (state, num) {
      state.count += num
    }
 }
# 触发方式一
// 不传参
this.$store.commit('add')
// 传参
this.$store.commit('addNum',5)
# 触发方式二
// 需要使用数据的组件.vue

// 导入mapMutations
import { mapMutations } from 'vuex'

// 利用扩展运算符设置为该组件的方法
methods: {
    ...mapMutations(['add','addNum'])
}

// 在template中直接使用
<button @click='add'>+1<button>
    
// 传参
<button @click='add(5)'>+5<button>

# 3.4 actions: 异步操作数据

// 专门进行异步操作的属性
  actions: {
    addAsync (content) {
      setTimeout(() => {
        content.commit('add')
      }, 1000)
    },
    addAsyncNum (content, step) {
      setTimeout(() => {
        content.commit('addNum', step)
      }, 1000)
    }
  }
# 触发方式一
// 可以通过$store.dispatch()触发
this.$store.dispatch('addAsync')
// 传参
this.$store.dispatch('addAsyncNum',5)
# 触发方式二
// 需要使用数据的组件.vue

// 导入mapActions
import { mapActions } from 'vuex'

// 利用扩展运算符设置为该组件的方法
methods: {
    ...mapActions(['subAsync', 'subAsyncNum'])
}

// 在template中直接使用
<button @click='subAsync'>异步+1<button>
    
// 传参
<button @click='subAsyncNum(5)'>异步+5<button>