vuex:是一个专为 Vue.js 应用程序开发的状态管理模式 + 库
一般会在Vuex 中存放一些需要在多个界面中进行共享的信息。比如登录状态、登录人,商品信息等,可以放在统一vuex中进行管理。
使用:
1、在store文件夹中创建一个js
2、在main.js中引用
import Vue from 'vue'
import Vuex from 'vuex'
import app from './modules/app'
import user from './modules/user'
import permission from './modules/async-router'
import getters from './getters'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
app,
user,
permission
},
//state:共享状态,可以理解为变量
//this.$store.state.xxx
state: {
NewprojectMainData: [], //最后提交的项目信息
pmdAllDictItems: {}, // 要使用的数据字典,格式为 groupName:[字典项的集合]
ProjectCreator: '',//登录人
},
//Mutation:更改vuex的store中state的唯一方法
//只有通过提交mutation才能修改状态(变量值)mutation 必须是同步函数,计算,定义一些方法
//使用:
//this.$store.commit('setNewprojectMainData'.value)(同步)
//this.$store.dispatch('setNewprojectMainData'.value)(异步)
mutations: {
setNewprojectMainData(state, value) {
state.NewprojectMainData = value
},
setAllDict(state, value) {
state.pmdAllDictItems = value
},
setProjectCreator(state, value) {
state.ProjectCreator = value
}
},
//action 相似于 mutation,不一样在于:action 提交的是 mutation
//而不是直接变动状态。Action 可以包含任意异步操作
actions: {},
//this.$store.getter.xxx
//Getter:基于state的派生状态,可理解为组件中的计算属性,在数据展示前进行一些变化处理
//具有缓存功能,能够提高运行效率
getters: {
...getters,
getNewprojectMainData(state) {
return state.NewprojectMainData
},
// 输入groupName和value获取中文值
getNamecnByGroupNameAndValue: (state) => (groupName, value) => {
if (state.pmdAllDictItems[groupName].filter(a => a.value == value).length == 0) {
return ''
}
return state.pmdAllDictItems[groupName].find(a => a.value == value).namecn
},
creator: (state) => (ProjectCreator) => {
const creator = JSON.parse(window.localStorage.getItem('user_info')).ebsUserId
if (creator == ProjectCreator) {
return true
} else {
return false
}
}
},
//Module:模块,在大型项目中为了方便状态的管理和协作开发将store拆分为多个子模块(modules)
//每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割
modules:{
moduleA: moduleDemo
}
})
//模块
const moduleDemo = {
state: {
ebsInfo: []
},
mutations: {
setebsInfo(state, value) {
state.ebsInfo = value
}
},
getters: {
},
actions: {},
}
使用:
//在App.vue初始化界面中使用这样就不用每个界面都赋值一次避免重复操作
const ProjectCreator = project.created_by//获取登录人
this.$store.commit('setProjectCreator', ProjectCreator) //通过Mutation修改登录人
this.$store.state.ProjectCreator//获取修改后的登录人
//在具体要使用的界面中使用
data() {
return {
//用于判断当前操作人是否是当前登录人,写在data全局中
creator:this.$store.getters.creator(this.$store.state.ProjectCreator),
}
}
//使用
methods: {
onSubmit() {
if (this.creator) {
//进行接下来的操作
}
}
}
//模块化的使用
this.$store.commit('setEbsInfo', value)//修改
this.$store.state.moduleA.ebsInfo//使用