vuex
状态管理vuex,之前一般都是通过一个全局js文件实现全局设置,在vue中通过vuex进行管理
简介
vuex是专为vue.js应用程序开发的状态管理模式。它采用集中存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。vuex也集成到了官方调试工具devtools extension,提供了诸如零配置的time-travel调试、状态快照导入导出等高级调试功能。
“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。Vuex 和单纯的全局对象有以下两点不同:
Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们通过一些工具帮助我们更好地了解我们的应用
核心内容
状态管理有5个核心,分别是state、getter、mutation、action以及module。分别简单的介绍一下它们:
1、state
state为单一状态树,在state中需要定义我们所需要管理的数组、对象、字符串等等,只有在state状态树中定义过,在vue.js的组件中才能获取你定义的对象的状态。
2、getter
getter有点类似vue.js的计算属性,当我们需要从store的state中派生出一些状态,那么我们就需要使用getter,getter会接收state作为第一个参数,而且getter的返回值会根据它的依赖被缓存起来,只有getter中的依赖值(state中的某个需要派生状态的值)发生改变的时候才会被重新计算。
3、mutation
更改store中state状态的唯一方法就是提交mutation,就类似事件。每个mutation都有一个字符串类型的事件类型和一个回调函数,我们需要改变state的值就要在回调函数中改变。我们要执行这个回调函数,那么我们需要执行一个相应的调用方法:store.commit。
4、action
action可以提交mutation,在action中可以执行store.commit,而且action中可以有任何的异步操作。在页面中如果我们要调用这个action,则需要执行store.dispatch
5、module
module其实只是解决了当state中很复杂臃肿的时候,module可以将store分割成模块,每个模块中拥有自己的state、mutation、action和getter。
使用
使用vue/cli初始化项目的时候选择vuex
或者之后引入:
npm install vuex --save
版本:
“vuex”: “^4.0.2”
而后建立一个store文件夹,建立一个index.js
store/index.js
默认的创建状态管理的文件
import {createStore} from "vuex";
export default createStore({
state: {//全局状态
typeList: [],
formVisible: false,
formIndex: null,
projectList: []
},
//被多次使用的状态的处理结果,可以添加getters的处理方法
getters: {
getProjectList: state => {
return state.projectList.filter(item => item.pageURL !== '')
},
},
//触发状态直接发生变化
mutations: {
typeListAsync(state, data) {
state.typeList = data;
},
changeFormVisible(state, index) {
state.formIndex = index;
state.formVisible = !state.formVisible;
},
projectListAsync(state, data) {
state.projectList = data;
}
},
//触发异步的状态变化
actions: {
async typeListAsync(context) {//typeListAsync({commit})
// return context.commit('typeListAsync', ["sams"])
return http.get("/modules", {
file: 'modules',
}, (res) => {
context.commit('typeListAsync', res.data);
})
},
async changeProjectAsync(context, param) {
param.file = 'project';
console.log("changeProjectAsync", param);
return http.post("/operation", param, (res) => {
context.commit('projectListAsync', res.data);
})
},
async getProjectListAsync(context) {
// return context.commit('typeListAsync', ["sams"])
//异步 aixos 异步
return http.get("/search", {
file: 'project',
}, (res) => {
console.log("getProjectListAsync");
context.commit('projectListAsync', res.data);
})
}
},
modules: {}
});
vue2.x一般通过以下方式引入vue的实例
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
vue3.x一般通过以下方式引入vue的实例
createApp(App).use(store).mount("#app")
以下对于vuex的应用主要是vue2.x的用法,在vue3中需要将this.$store
换成:
//vue2.x
//this.$store.state.formVisible
//vue3.x
import { useStore } from 'vuex';
const store = useStore();
store.state.formVisible
store/index.js 文件说明
需要管理的状态,也即以前的需要全局维护的变量,这里主要是维护组件之间都需要使用的数据
获取store中的state值
页面中获取status的值可以直接通过以下方式获取
this.$store.state.formVisible
但是依赖state的值获取到的结果,必须在页面中的计算属性computed中获取,以实现响应性,否则当state对应值发生变化的时候无法正常获取到变化的值,页面没有对应更新,上述取值不可直接使用
computed: {
getVisible() {
return !this.$store.state.formVisible;
}
}
获取store中的state值的处理结果–getters
该方式主要是用于多次获取需要使用特殊处理的state的值getters
:
被多次使用的状态state的处理结果,可以添加getters的处理方法
通过在getters中添加方法,可以使得每次state变更触发对应的getter方法,否则就使用之前的缓存即可
页面中获取status的值可以直接通过以下方式获取
this.$store.state.formVisible
但是如果想保证state的响应性,必须通过计算属性computed中获取,否则当state对应值发生变化的时候无法正常获取到变化的值,页面没有对应更新
computed: {
getProjectList() {
//return this.$store.state.typeList; 若是不需要处理
return this.$store.getters.getProjectList;//需要处理
}
}
store.state.prop不可以直接使用在.vue文件的template中,必须通过computed 引用以保留响应性
同步更改store中的state值-mutations
vuex在mutations中直接改变状态中state的值
mutations 中修改state值
mutations: {
typeListAsync(state, data) {
state.typeList = data;
},
}
触发store中的mutations方法
页面中通过以下方式触发mutations中的方法:
this.$store.commit(“typeListAsync”);
如果存在参数,直接传递即可
this.$store.commit(“typeListAsync”,null);
mutation 都是同步事务,因此如果存在异步事务,需要处理异步事务的action
异步更改store中的state值-action
action 类似于 mutation,不同在于:
- action 提交 mutation,由mutation改变状态值,而不是直接变更状态值。
- action 可以包含任意
异步
操作。
action 中修改state值
在action方法中通过以下方式触发mutation的方法进行state的值变更
context.commit('projectListAsync',data);
触发store中的action方法
页面中通过以下方式触发action中的方法:
this.$store.dispatch("changeProjectAsync");
如果存在参数,直接传递即可
this.$store.dispatch("changeProjectAsync",param);
store中的action之间的触发
context.dispatch('getUserMenus')
actions: {
async login(context, param) {
//异步 aixos 异步
return http.post(`/login`, param).then((res: any) => {
context.dispatch('getUserMenus')
})
},
async logout(context) {
return http.get(`/logout`).then((res: any) => {
})
},
async getUserMenus(context) {
return http.get('vvvvv/vv').then((res: any) => {
})
}
},
多模块需要状态管理
modules,是多模块时使用的,一般简单的项目不需要使用
vue2.x的应用
设置多模块的时候用于确定当前option是否使用命名空间namespaced:true
modules
export default {
namespaced:true,//设置多模块的时候用于确定当前option是否使用命名空间
state: {
post:""
},
getters: {
},
mutations: {
},
actions: {
}
}
引入modules,正常的store文件中添加
import postModules from '/xxx'
export default new Vuex.Store( {
state: {
},
getters: {
},
mutations: {
},
actions: {
},
modules: {
postModules
}
})
vue3.x的应用
modules:
export default {
state: {
post:""
},
getters: {
},
mutations: {
},
actions: {
}
}
引入modules,正常的store文件中添加
import postModules from '/xxx'
export default createStore({
state: {
},
getters: {
},
mutations: {
},
actions: {
},
modules: {
user:postModules
}
}
获取多模块的状态值
import {mapGetters,mapState} from 'vuex'
computed:{
...mapGetters("postModules",['post'])
}
computed:{
...mapState(["stateName"])//引用 stateName 为计算属性
...mapState({
anotherName:"stateName",
anotherName:state=>state.stateName,//引用 默认 store的属性
anotherName:state=>state.moduleName.stateName,//引用store 多模块内的属性
})//引用store中state的 stateName 计算属性,并重命名
...mapState("moduleName",["stateName"])//引用store中多模块state的 stateName 计算属性
...mapState("moduleName",{//引用store中多模块state的 stateName 计算属性,并重命名
anotherName:"stateName",
anotherName:state=>state.stateName
})
...mapGetters("moduleName",["FunctionName"]),
...mapActions("moduleName",["FunctionName"]),
getStateProp(){
return this.$store.state.modulesName["stateProp"]//可以取到多模块state的值
}
getStateProp(){
return this.$store.state.stateProp//可以取到state值
}
getModuleGetter(){
//this.$store.getters.modulesName["gettersProps"]//该方式无法取值
//只能使用该方式
return this.$store.getters["modulesName/gettersProps"]
}
}
触发更改state值
this.$store.dispatch("modulesName/changeProjectAsync");
namespaced 的 module模块获取根store中的值
export default {
namespaced:true,//设置多模块的时候用于确定当前option是否使用命名空间
state: {
post:""
},
getters: {
getRoot(state,getters,rootState){
return `${ rootState.typeList }`
}
},
mutations: {
},
actions: {
function(state,getters,rootState){
}
}
}