Vue.js学习笔记(拾肆)

83 阅读1分钟

【6月日新计划更文活动】第4天

VueX getters 的使用

1、概念:当 state 中的数据需要经过加工后再使用时,可以使用 getters 加工

2、在 store.js 中追加 getters 设置

......
// 准备 getters —— 用于将 state 中的数据进行加工
const getters = {
    bigSum(state) {
        return state.sum * 10
    }
}
// 创建并暴露 store
// 创建并暴露 store
export default new Vuex.Store({
        ......
    state
})

3、组件中读取数据: $store.getters.bigSum

四个 map 方法的使用

1、mapState 方法:用于帮助我们映射 state 中的数据作为计算属性

 computed: {
   //借助 mapState 生成计算属性,从state 中读取数据。(对象写法)
   // ...mapState({ he: "sum", xuexiao: "school", xueke: "subject" }),

   //借助 mapState 生成计算属性,从state 中读取数据。(数组写法)
   ...mapState(["sum", "school", "subject"]),
 },

2、mapGetters 方法:用于帮助我们映射 getters 中的数据作为计算属性

 computed: {
   // 借助 mapGetter 生成计算属性,从 getters 中获取数据。(对象写法)
   // ...mapGetters({ bigSum: "bigSum" }),
   // 借助 mapGetter 生成计算属性,从 getters 中获取数据。(数组写法)
   ...mapGetters(["bigSum"]),
 },

3、mapActions 方法:用于帮助我们生成与 actions 对话的方法。即:包含 $store.dispatch(xxx) 的函数

methods: {
  // // 借助 mapActions 生成对应的方法,方法中会调用 dispatch 去联系。(对象写法)
  // ...mapActions({ singular: "jiaOdd", increaseWait: "jiaWait" }),
  // 借助 mapActions 生成对应的方法,方法中会调用 dispatch 去联系。(数组写法)
  ...mapActions(["jiaOdd", "jiaWait"]),
},

4、mapMutations 方法:用于帮助我们生成与 mutations 对话的方法,即:$store.commit(xxx) 的函数

methods: {
  // // 借助 mapMutations 生成对应的方法,方法中会调用 commit 去联系 mutations (对象写法)
  // ...mapMutations({ increase: "JIA", decrease: "JIAN" }),

  // 借助 mapMutations 生成对应的方法,方法中会调用 commit 去联系 mutations (数组写法)
  ...mapMutations(["JIA", "JIAN"]),
 }

备注:mapActions 与 mapMutations 使用时,若需要传递参数、需要:在模板中绑定事件时传递好参数,否则参数是事件对象。

模块化 + 命名空间

1、目的:让代码更好维护,让多种数据分类更加明确

2、修改 store.js

const countOptions = {
    namespaced: true,    // 开启命名空间
    actions:  {    ......    },
    mutations: {    ......    },
    state: {    ......    },    // 储存数据
    getters: {
        bigSum(state) {
            return state.sum * 10
        }
    },
}

// person相关的配置
const personOptions = {
        namespaced: true,    // 开启命名空间
    actions:  {    ......    },
    mutations: {    ......    },
    state: {    ......    },    
}

// 创建并暴露 store
export default new Vuex.Store({
    // 必须模块化导出       命名空间设置为true。 namespaced:true
    modules: {
        countAbout: countOptions,
        personAbout: personOptions
    }
})

3、开启命名空间后,组件中读取 state 数据

//方式一:自己直接读取
this.$store.state.countAbout.sum
//方式二:借助 mapState 读取
...mapState(["sum", "school", "subject"]),

4、开启命名空间后,组件中读取 getters 数据

// 方式壹:直接读取
this.$store.getters['personAbout/firstPersonName']
// 方式贰:借助 mapGetters
...mapGetters("countAbout", ["bigSum"]),

5、开启命名空间后,组件中调用 dispatch

// 方式壹:直接 dispatch
this.$store.dispatch("personAbout/addPersonWang", personObj)
// 方式贰:借助 mapActions
...mapActions("countAbout", ["jiaOdd", "jiaWait"]),

6、开启命名空间后,组件中调用 commit

// 方式壹:直接 commit儿
this.$store.commit("personAbout/ADD_PERSON", personObj);
// 方式贰:借助 mapMutations
...mapMutations("countAbout", ["JIA", "JIAN"]),