前端Vue2-Day59

getters配置项:加工state中的数据进行使用。(类似于computed)

getters和state的关系类似于computed和data的关系

配置:

const getters = {
  demo() {
    return ...
  }
},
export default new vuex.Store({
  ...
  getters,
})

组件中读取:$store.getters.xxx

 

四大map方法的使用:用于优化组件中computed和methods

配置时均需要使用...剩余运算符,将四种map方法内的值结构至配置项内。

mapState:映射state中的数据转化为组件的计算属性。

computed: {
  // 对象写法
  ...mapState({
    demo1:'demo1',
    demo2:'demo2'
  })
  // 数组写法(同名)
  ...mapState(['demo1', 'demo2'])
}

数据加引号:意为去state中寻找同名属性,若不加引号则在当前组件中寻找属性则报错。

 

mapGetters:映射getters中的数据转化为组件中的计算属性。

computed: {
  // 对象写法
  ...mapGetters({
    demo1:'demo1',
    demo2:'demo2'
  })
  // 数组写法(同名)
  ...mapGetters(['demo1', 'demo2'])
}

 

使用mapActions和mapMutations,需要在模板内调用方法时传入参数,否则会默认传参event!

mapActions:用于帮助我们生成和actions对话的方法,即调用$store.dispatch

methods: {
  ...mapActions({
    demo:'demo'
  })
  ...mapActions(['demo'])
},

 

mapMutations:用于帮助我们生成和actions对话的方法,即调$store.dispatch

methods: {
  ...mapMutations({
    demo:'demo'
  })
  ...mapMutations(['demo'])
},

 

Vuex模块化+命名空间:使代码易于维护,数据分类更加明确。

① 修改store配置文件:

const part1 = {
    // 开启命名空间!
    namespaced: true,
    state: { datas },
    getters: {
        datas() {
            return ...
        },
    },
    actions: { ... },
    mutations: { ... },
}
const part2 = {
    namespaced: true,
    state: { datas },
    getters: {
        datas() {
            return ...
        },
    },
    actions: { ... },
    mutations: { ... },
}

export default new Vuex.Store({
    modules: {
        part1,
        part2
    }
})

② 组件中使用:

// 开启命名空间后组件中读取 state数据
computed: {
    // 直接读取(xxx为模块名)
    demo() {
        return this.$store.state.xxx.data
    },
    // 借用mapState读取
    ...mapState('xxx', ['data'])
},
// 开启命名空间后组件中读取 getters数据
computed: {
    // 直接读取
    demo() {
        return this.$store.getters['xxx/data']
    },
    // 借用mapGetters
    ...mapGetters('xxx', ['data'])
},
// 开启命名空间后组件中调用 dispatch
methods: {
    // 直接读取
    fun() {
        this.$store.dispatch('xxx/fun', data)
    },
    ...mapActions('xxx', ['fun'])
},
// 开启命名空间后组件中调用 commit
methods: {
    // 直接读取
    fun() {
        this.$store.commit('xxx/fun', data)
    },
    ...mapMutations('xxx', ['fun'])
},

 

使用map方法在组件中获取传输state和getters与提交Actions和Mutations时,可以重复名调用的方法和数据。

只需将数组形式变为对象形式即可!

...mapState("part", {
  重命名:"原名称"
})

...mapGetters("part", {
  重命名:"原名称"
})

...mapActions和...mapMutations同理

 

posted @ 2022-10-26 11:40  HM-7  阅读(30)  评论(0)    收藏  举报