vuex store使用总结 3 (模块化的使用 )

vuex store使用总结 1 ( 简单使用 )

vuex store使用总结 2 ( 功能化的使用 )

请先翻看前 两节 再看这里的内容

https://vuex.vuejs.org/zh/guide/modules.html
 

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

随着项目的扩大, 上一章节的 提供的方式 已经 满足不了我们的需求了。 所以呢 我们对他进行模块化的处理,对他们进行改造

现在 store 文件夹结构 变成这样了

index.js

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

import moduleAchat from '/module/moduleA/ChatInfo.js'
import moduleAuser from '/module/moduleA/UserInfo.js'

Vue.use(Vuex)

export const store = new Vuex.Store({
	modules:{
		chat:moduleAchat,
		user:moduleAuser
	}
})

store.state.chat   // 获取moduleAchat

store.state.user   // 获取moduleAuser

ChatInfo.js

const state = {
	//设置属性 用来存储数据
	message: {}
	name: {}
}

const getters = {

}

const mutations = {
	//更改用户状态信息
	setLocalUser(state, data) {
		if (data) {
			state.name = data
		} else {
			state.name = null
		}
	},
	//更改属性的状态
	setMessage(state, data) {
		state.message = data
	}
}

const actions = {

}

export default {
	state,
	getters,
	mutations,
	actions
}

UserInfo.js

const state = {
	//设置属性 用来存储数据
	message: {},
	localuser: {},
	isLogin: false
}

const getters = {
	//对应方法 用来获取属性的状态
	getMessage: state => state.message
}

const mutations = {
	//更改属性的状态
	setMessage(state, data) {
		state.message = data
	}
}

const actions = {
	//应用 mutation
	setUser({
		commit
	}, data) {
		commit('setMessage', data)
	}
}

export default {
	state,
	getters,
	mutations,
	actions
}

是不是 感觉越用越简单了

这里就是 Vuex  模块化使用的全部内容了

 chat:moduleAchat,
 user:moduleAuser

其实还能再对他继续进行扩充:

目前  state getter mutations action 都是在一个文件中;

可以吧他们 分别 分成四个文件 和一个 index !

大于更加大型的 目前可以这么搞!

目前我的 项目够用了, 强加上去没有好处反而 有害


 

另外两篇:

Logo

前往低代码交流专区

更多推荐