vuex state全局共享(详细讲解)

425 阅读1分钟

Vuex

作用

用于保存全局共享的数据

state

  • 用于存放全局共享的数据
  • 用法

    new Vuex.Store({
        state: {
            属性名: 属性值
        }
    })
    
  • 在组件里面 访问 state 里面的数据

    第一种:this.$store.state.属性名

    第二种:需要在 组件里面 使用 按需导入 得到 mapState 将mapState 映射为当前组件的计算属性

    ```
    import { mapState } from 'vuex'
    ...mapState(['属性名'])
    ```
    

mutation

  • 用于修改 state 里面的数据

  • 语法

    mutations: {
        函数名(state, payload) {
            // state 就代表了 state 对象
            // state.属性名  可以访问 state 对象里面的属性
            state.属性名 = payload
        }
    }
    
  • 在组件里面 访问

    使用 this.$store.commit('函数名', 参数)

    需要在 组件里面 使用 按需导入 得到 mapMutations 映射为当前组件的 methods

    ```
    import { mapMutations } from 'vuex'
    ...mapMutations(['函数名'])
    ```
    

actions

  • 作用:用于发送异步请求

  • 语法

    actions: {
        函数名(context, payload) {
            // context 表示 new Vuex.Store 实例对象
            context.commit('mutations里面的函数', paload)
        }
    }
    
  • 在组件里面访问

    this.$store.dispatch('函数名', 参数)

    需要在 组件里面 使用 按需导入 得到 mapActions 映射为当前组件的 methods

    ```
    import { mapActions   } from 'vuex'
    ...mapActions  (['函数名'])
    ```
    

getters

  • 作用:相当于 组件 内部的 计算属性

  • 语法

    getters: {
        函数名(state) {
            // state 就是 代表 state 对象
        }
    }
    
  • 在组件里面访问

    this.$store.getters.属性

    需要在 组件里面 使用 按需导入 得到 mapGetters 映射为当前组件的计算属性

    ```
    import { mapGetters     } from 'vuex'
    ...mapGetters (['函数名'])
    ```
    

modules

  • 作用:用于将 vuex 划分成 模块
  • 语法:

    创建一个 xxxx.js 文件 文件里面 有4个核心成员

    ```
    export default {
        namespaced: true,
        state: () => ({}),
        mutations: {},
        actions: {},
        getters: {}
    }
    ```
    
  • 在 index.js 里面 导入

  import 模块对象 from '模块的路径'
  new Vuex.Store({
      modules: {
          模块名: 模块对象
      }
  })
  • 开启了 命名空间 以后 访问 模块里面的成员

  • 推荐使用 辅助函数的方法

    访问 state 里面 ...mapState('模块名', ['属性名'])

    访问 mutations 里面的 函数 ...mapMutations('模块名', ['函数名'])

       this.$store.commit('模块名/函数名')
    

    访问 actions 里面的函数 ...mapActions('模块名', ['函数名'])

       this.$store.dispatch('模块名/函数名')
    

    访问 getters 里面的计算属性 ...mapGetters('模块名', ['函数名'])