08-Vuex

Vuex

一、简介

  ① 是什么:是一个状态管理工具,存放项目组件中的公共数据

二、使用语法

  ① 语法

    -1. 创建 Vuex 实例

const store = new Vuex.Store({
    state:{
        // 用来存放组件公共数据
    },
    getters:{
        // 用来过滤读取数据
        方法名(state){
            //...
        }
    },
    mutations:{
        //用来操作更新数据
        方法名(state,数据1,....,数据n){
            // 操作数据
            state.键 = 操作
            //...
        }
    },
    actions:{
        //也是用来更新数据,异步请求
        方法名(context){
            // 调用 mutations 中的方法
            context.commit('方法名',数据1,....,数据n)
            //...
        }
    }
})

    -2. 激活 Vuex 和 使用语法   

new Vue({
    //激活
    store,
    //....,
    methods:{
        // 调用 Vuex 中 actions 方法
        this.$store.dispatch('方法名')
        // 调用 Vuex 中 mutations 方法
        this.$store.commit('方法名')
    },
    computeds:{
        方法名(){
            // 使用 Vuex 中数据
            return this.$store.state.键
        }        
    }
})

###注意

  ①  Vuex 中 actions 无法直接操作 state 数据,需要通过 mutations 操作

  ② 操作 mutations 中的方法 ,使用 commit(' 方法名 ')触发

  ③ 操作 actions 中的方法,使用 dispatch (' 方法名 ')  触发

三、辅助函数

  ① 语法( 在Vuex 库中)

    --1. state 辅助函数: Vuex.mapState([ ' 键1 ',....,' 键n ' ])

    --2. getter辅助函数:Vuex.mapGetters([ ' 方法名1 ',.....,' 方法名n ' ])

    --3. mutation 辅助函数:

Vuex.mapMutations(['方法名1',....,'方法名n'])    // 此时 普通函数方法名同数组里的值

  或

Vuex.mapMutations({
    键:值,
    //...
})    
// 此时 普通函数方法名为键名,值 为mutations中的方法名   

    --4. actions 辅助函数

Vuex.mapActions(['方法名1',....,'方法名n'])    // 此时 普通函数方法名同数组里的值

  或

Vuex.mapMutations({
    键:值,
    //...
})    
// 此时 普通函数方法名为键名,值 为actions中的方法名

###注意:

  -- 当辅助函数 参数 为 对象 或 数组 时,普通函数名的对应方式

四、模块化语法

  ① 定义阶段

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

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

const store = new Vuex.Store({
  // 公共的
  state
  getters
  mutations
  actions

  // 单个模块的
  modules: {
    a: moduleA,
    b: moduleB
  }
})

//在new vue中激活

  ② 调用阶段

// 它们都是在computed
...mapState({
    方法名: state => state.状态,
    方法名: state => state.moduleA.状态,
    方法名: state => state.moduleB.状态
}),
...mapGetters({
    方法名: '方法名',
    方法名: 'moduleA/方法名',
    方法名: 'moduleB/方法名'
})

// 它们都是在methods
...mapMutations({
    方法名: 'moduleA/方法名',
    方法名: 'moduleB/方法名'
}),
...mapActions({
    方法名: 'moduleA/方法名',
    方法名: 'moduleB/方法名',
})
特此声明:如需转载请注明出处,如有疑问请及时提出以便于改正,如有侵权,联系删除,谢谢
原文地址:https://www.cnblogs.com/CGWTQ/p/11989959.html