详解Vuex下Store的模块化拆分实践(2)

<template> ········· </template> <script> import { mapState, mapActions, mapGetters } from 'vuex' module.exports = { ······· methods: { ...mapActions([ 'fetchList' ]) }, computed: { ...mapState{ list: state => state.list }, ...mapGetters{[ 'hotList' ]} } } </script> <style> ······· </style>

复用模块

模块化拆分之后可以实现较为复杂的数据流,特别地,如果对action和mutation稍加改造,就可以复用模块:
比如我们在Example.vue中发起Action:

Example.vue

<template> ········· </template> <script> import { mapState, mapActions, mapGetters } from 'vuex' module.exports = { ······· mounted () { this.fetchList({ request: 'week' }) }, methods: { ...mapActions([ 'fetchList' ]) }, computed: { ...mapState{ list: state => state.list }, ...mapGetters{[ 'hotList' ]} } } </script> <style> ······· </style>

在上面的例子中,我们在组件挂载完成之后发起了一个fetchList的action,并添加了一个名为request的参数,这里给一个week值,也可以给按照业务需要给month、year之类的值,接下来对aAction.js做一些修改。

actions/aAction.js

import { FETCH_LIST_REQUEST, FETCH_LIST_SUCCESS, FETCH_LISR_FAILURE } from '../constants/types' import { toQueryString } from '../../utils' import axios from 'axios' export const fetchListAction = { fetchList ({ commit, state }, param) { commit(FETCH_LIST_REQUEST, { request: param['request'] }) axios.get(`${param['request']}list`) .then(function (response) { commit(FETCH_LIST_SUCCESS, { request: param['request'] data: response.data }) console.log(response); }) .catch(function (error) { commit(FETCH_LIST_FAILURE, { request: param['request'] error: error }) console.log(error); }); } }

请求成功之后,在 commit()中加入了一个request的参数,这样Mutation就可以从里面获取相应的参数,最后对aMutation做一些修改。

mutations/aMutation.js

import { FETCH_LIST_REQUEST, FETCH_LIST_SUCCESS, FETCH_LISR_FAILURE } from '../constants/types' export const fetchListMutation = { [FETCH_LIST_REQUEST] (state, action) { state[action.request].isFetching = true }, [FETCH_LIST_SUCCESS] (state, action) { state[action.request].isFetching = false state[action.request].data = action.data state[action.request].lastUpdated = (new Date()).getTime() }, [FETCH_LIST_FAILURE] (state, action) { state[action.request].isFetching = false state[action.request].error = action.error } }

state加入了[action.request],以区分不同的接口数据。

完成以上修改后,只需要在组件调用相应的action时加入不同的参数,就可以调用相同类型但数据不同的接口。

总结

以上是我在Vuex实践中总结的一些东西,分享给大家,如果有不合理或者错误❌的地方,也希望各位老司机不吝赐教,有机会多交流。也希望大家多多支持脚本之家。

微信号:pasturn
Github:https://github.com/pasturn

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/1ade03f55d3c20f791d832ad913a51b3.html