【vue2的store】

整理store

store都包含state、getters、mutations、actions、modules、

state

类似于data用来声明响应式数据的地方

state:{
        socket:null
    },

mutations

用来写方法改变state的值的地方,不过都是同步的修改

 "SET_SOCKET":(state,socket)=>{ //此处必须传入一个state,后面是调用传入的值
            state.socket = socket
        }
        //调用的方法
  this.$store.commit('SET_SOCKET',3) //3为传入的参数

getters

类似于computed,getter的返回值 会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算

getters: {
        getNumber: state => {
            retrun state.list.filter(item => item > 5)
        }
    } 

actions

异步修改states的值,里面可以调用mutations里的方法

actions:{
	        cleanUserInfo({commit}){
	            commit('SET_USER_INFO','')
	        },//这里展示调用mutations里的方法SET_USER_INFO,传入空参数
	        async getCurrentUser({commit},ts){
	            try{
	               let {data}= await getCurrentUser(ts)
	                commit('SET_USER_INFO',data)
	                Storage.setItem('userInfo',data)
	            }catch (e){
	                return Promise.reject(e)
	            }

        	},//这里展示发送异步请求后调用SET_USER_INFO方法,并将userInfo存入本地Storage
        }
//在外部调用actions
await this.$store.dispatch("cleanUserInfo");//没有参数的
await this.$store.dispatch("resetMenu", null, { root: true });//用参数的

modules

如果store过于冗杂,可以将store按功能模块进行划分,modules就能实现这个功能。

import moduleA from '@/store/modules/moduleA'//在index.js中引入
 // 就是使用modules属性在进行注册两个状态管理模块
  modules: {
    moduleA,
  }

还有一种比较复杂的方式,首先在store文件夹下建立modules文件夹,将模块写在文件夹中
然后就是引用和创建

export default {//这是下文的getters
    userInfo:(state)=>state.user.userInfo,
    auths:(state)=>state.user.authArray,
    systemRoutes:(state)=>state.system.routes,
    subSystem:(state)=>state.system.subSystem,
    firstRoute:(state)=>state.system.systemFirstRoute,
    tagViews: (state) => state.tagView.tagsViews,
    currentViews: (state) => state.tagView.currentTag,
    threed: (state) => state.threed.status,
}
import {createStore} from 'vuex'
import getters from "@/store/getters";

let files = require.context('./modules', false, /\.js$/);
// (创建出)一个 context,其中所有文件都来自./modules文件夹,request 以 `.js` 结尾。
let modules = {}
files.keys().forEach(key => {
    modules[key.replace(/(\.\/|\.js$)/g, '')] = files(key).default
    //modules[key.replace(/(\.\/|\.js$)/g, '')]给modules对象赋值,去掉可以的.js后缀
})

export default createStore({
    modules,
    getters
})
await this.$store.dispatch("user/cleanUserInfo",参数,{root: true});//有modules的使用actions {root: true}此处的root:true表示非本模块的action
this.$store.commit("user/cleanUserInfo");//有modules的使用mutations
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值