vuex 模块化使用

对vuex数据流图加入了一些自己的理解内容

一、模块配置

目录结构

 模块代码文件 moduleA.js

const state = {
	"username": "foo",
	"age": 18
}

const getters = {
	// getAge(state) {
	// 	return (n) => {
	// 		return state.age += n;
	// 	}
	// }
	getAge(state) {
		return state.age + 10;
	}
}

const mutations = {
	setAge(state, n) {
		state.age += n;
	}
}

const actions = {
	addCountDelay(context, n) {
		setTimeout(function() {
			context.commit('setAge', n)
		}, 2000);
	}
}

export default {
	namespaced: true, // 开启命名空间支持
	state,
	getters,
	mutations,
	actions
}

index.js对模块文件的引用

import Vue from 'vue';
import Vuex from 'vuex';

import mA from '@/store/modules/moduleA.js'

Vue.use(Vuex);

const store = new Vuex.Store({
	modules: {
		moduleA: {
			// namespaced : mA.namespaced,
			// state : mA.state,
			// getters : mA.getters,
			// mutations : mA.mutations,
			// actions : mA.actions
			...mA
		},
	}
})

export default store;

二、state

获取state的值,如果在多模块的情况下可以用两种方式使用mapState

computed: {
    		// 第一种
			...mapState('moduleA', ['username', 'age']),
    
			// 第二种
			...mapState({
				username: (state) => state.moduleA.username,
				age: (state) => state.moduleA.age
			}),
	}

三、getter

getter是store的计算属性,对state的加工,是派生出来的数据。

computed: {
    getAge() {
        // getters中加入了命名空间后对值的获取
        return this.$store.getters["moduleA/getAge"];
    }
}

在多模块中使用mapGetters

computed: {
	...mapGetters('moduleA', ['getAge']),    
    })
}

四、mutation

mutation是唯一的修改state的方式,如果是同步方式可以直接从method中使用commit方法进行提交,跳过action内容,多模块中调用mutation中的方法

methods: {
    setAge() {
        this.$store.commit('moduleA/setAge', 26);
    },
    // ...mapMutations("moduleA", ['setAge']),
},

多模块中使用mapMutations

methods: {
    ...mapMutations("moduleA", ['setAge']),
},

五、action

action 提交的是 mutation,通过 mutation 来改变 state ,而不是直接变更状态。action 可以包含任意异步操作。多模块中对action的使用

methods: {
    addCountDelay() {
        this.$store.dispatch('addCountDelay', 20);
    }
},

多模块中对mapActions的使用

methods: {
	...mapActions("moduleA", ['addCountDelay'])
},

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值