一、简单状态管理示例,不使用module
1、实例化一个vuex对象,并抛出
const store = new Vuex.Store({
state:{ //定义属性, 进行状态管理
data:0
},
mutations:{ //同步方法,修改state值
changeProductMu(state,params){
state.data=params;
}
},
actions:{ //异步方法,通过commit去调用mutations方法去修改state状态,或者通过dispatch,提交到actions中可请求后台地址
changeProductAction({commit},params){
commit('changeProductMu',params);
dispatch('marking/getUsersTaskSet', null, { root: true }) //对应的marking.js的actions中找getUsersTaskSet方法
}
},
getters:{ //计算属性,state的值变化,它会同步进行变化
doubleGet(state){
return state.data*2+50
}
},
modules:{} //模块化,一般用于项目较大的时候使用
})
export default store
2、列表页面获取store中值,则可在页面中{{dataValue}} 把对应值渲染出来
computed: {
dataValue() {
return this.$store.state.data;
},
},
3、列表页面中通过methods去调用store的方法
ByMutationchange() {
// 通过commit触发store.js中mutations并传参
this.$store.commit("changeProductMu", 10); // 此时state中的data值就变成10
},
ByActionchange() {
// 通过dispatch异步触发action并传参
this.$store.dispatch("changeProductAction", 100); // 此时data就变成100啦
},
ByGetterchange() {
this.$store.dispatch(
"changeProductAction",
this.$store.getters.doubleGet
); // 此时data可以通过getter来改变其值
},
二、使用module模块化进行状态管理
备注:一般在项目比较大情况下使用
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割
1、module的使用方法
- 项目结构
- 在store的index.js文件中进行组装
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
import common from './modules/common'
import tags from './modules/tags'
import getters from './getters'
Vue.use(Vuex)
//组装模块并导出
const store = new Vuex.Store({
modules: { //根节点相关
user,
common,
tags
},
//根节点相关
getters,
})
export default store
- 在main.js的vue中进行注册store
import router from './router'
import store from './store/index'
var vm = new Vue({
el: '#app',
router,
store,
components: {App},
template: '<App/>'
});
2、使用module
- 以module文件夹中的common.js为例,如果建立的只是给固定的组件common组件使用,在user.js文件中使用命名空间【namespaced: true,//使用命名空间,这样只在局部使用】
备注:给每个module 对象添加namespaced: true, 来达到命名空间来区分Module的效果,则在引用对应模块中方法,则需写上模块的命名
state 数据:=> this.$store.state.common.info (common是模块名字. info 是 state 里面的属性名字)
getters 数据: => this.$store.getters['common/getUserInfo'] (user namespace,模块名, getUserInfo 是 getter 的名字)
mutations => this.$store.commit( 'common/SAVE_LIST_PAGE_PARS', name); (AppKeepAlive 模块名, remove方法名, name 是荷载数据 payload)
export default {
//namespaced: true,//使用命名空间,这样只在局部使用
state: { //定义属性
data:10,
listPagePars: new Map() //记录页面查询参数
},
mutations: { //同步请求方法
//记录页面查询参数
SAVE_LIST_PAGE_PARS: (state, { path, pars }) => {
state.listPagePars.set(path, pars);
}
},
actions: { //异步请求方法
saveListPagePars: ({ commit }, { path, pars }) => {
commit('SAVE_LIST_PAGE_PARS', { path, pars });
}
}
}
- 在vue组件中发送请求
that.$store.dispatch("saveListPagePars", { //dispatch 异步请求
path: that.$route.path,
pars: that.page,
});
//或者使用commit同步提交数据
that.$store.commit("SAVE_LIST_PAGE_PARS",{
path: that.$route.path,
pars: that.page,
})