开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 10 天,点击查看活动详情
前言
有点懒惰了,感觉这是一项任务了。继续努力 不甘于平庸又不努力
2023继续!!!
Vuex
是专为Vue.js应用程序开发的状态管理模式。它采用集中式存储,管理应用中所有组件的状态。
作用:
- 统一状态管理,解决不同组件共享数据的问题
- 不同视图需要变更同一状态的问题
- 使用vuex之后,状态变化更加清晰
核心
- state
- 存放变量的对象,数据都是放在这里的。单一状态树
- 取值:
// 第一种:
this.$store.state
// 第二种:
...mapState({
// title: state => state.title
// title: "title"
title: state => {
return state.title;
}
})
- getter: 对象状态进行加工函数
- 对state中的数据进行加工
- 取值
// 第一种:this.$store.getter
// 第二种:
...mapGetter({
title: "title"
})
- mutation:修改state的状态,state的变化,都应该mutation去修改,方便追踪数据流转
- 注意:
- mutation函数必须是同步的
- mutation的type或者说是函数名可以用常量维护
- 调用
this.$store.commit('mutation类型(函数名)',参数) this.$store.commit({type:'mutation类型(函数名)'},...其他参数) - 注意:
const store = new Vuex.Store({
state:{count: 0}
mutations: {
increment(state, count) {
state.count = count
},
}
})
- action:执行异步操作,不能修改
- 类似于mutation,区别是
- action可以包含异步操作
- action不能直接修改state,需要触发mutation才能修改state
- 调用
mutation:{ CHANGE_TITLE(){} } actions: { // 通过context(上下文环境)可以触发mutation,触发action,获取state、getter等操作 // 第二个参数就是我们传递过来的参数 changeTitle(context,payload) { setTimeout(() => { context.commit(CHANGE_TITLE, payload) }, 1000); } } this.$store.dispatch('action名字','参数') this.$store.dispatch({type:'action类型(函数名)'},...其他参数) - 类似于mutation,区别是
- module: 模块
- 可以拆分成模块,每个模块都有自己的state,getter,mutation,actions
Vuex mutation 和 action
- mutation: 同步
- this.$store.commit('', data)
- action:异步
- this.$store.dispatch('', data)
- 可以使用then来判断异步的结束状态
actions:{ SET_NUMBER_A({commit},data){ return new Promise((resolve,reject) =>{ setTimeout(() =>{ commit('SET_NUMBER',10); resolve(); },2000) }) } } this.$store.dispatch('SET_NUMBER_A').then(() => { // ... })
getter mutation接收的第一个参数state,是全局的么?
是局部的
getter和mutation和action中怎么访问全局的state和getter?
-
在getter中可以通过
第三个参数rootState访问到全局的state,可以通过第四个参数rootGetters访问到全局的getter。 -
在mutation中
不可以访问全局的satat和getter,只能访问到局部的state。 -
在action中第一个参数context中的
context.rootState访问到全局的state,context.rootGetters访问到全局的getter。
Vuex模块的命名空间
避免耦合,要使模块具有更高的封装性和复用性,可以加下面参数 namespaced: true
怎么在带命名空间的模块内提交全局的mutation和action
将 { root: true } 作为第三参数传给 dispatch 或 commit 即可。
this.$store.dispatch('actionA', null, { root: true })
this.$store.commit('mutationA', null, { root: true })
vuex 怎么引入插件
const myPlugin = createPlugin()
const store = new Vuex.Store({
// ...
plugins: [myPlugin]
})
vuex刷新状态重置怎么解决
- 存入缓存(session中)
- 在接口请求之后确定状态
使用vuex-persistedstate状态持久化
import createPersistedState from "vuex-persistedstate"
const store = new Vuex.Store({
// ...
plugins: [createPersistedState({
storage: window.sessionStorage,
reducer(val) {
return {
// 只储存state中的user
user: val.user
}
}
}
)]
})
vuex,为什么需要用 mutation 这些来修改 state 数据,而不是直接更改
state是实时更新的,mutations只能同步操作。
可以总结为:单向数据流
后记
本文仅作为自己一个阅读记录,具体还是要看大佬们的文章