1.vuex的概念
vuex是专门为vue.js应用程序开发的状态管理模式。它采用集中式存储和管理程序的所有组件的数据。
2.vuex的好处
在大型的程序中如果多个组件中用到的数据我们可以存储到vuex中,如果小项目我们可以适当地使用vuex。
3.vuex五大核心及概念
- state:存储数据 在组件中的使用this.$store.state.属性名
- mutations:可以直接操作state中的数据,在组件中使用 this.$store.commit(‘方法名’,参数)
- actions:可以实现异步操作,在actions中操作mutations中的数据,在组件中使用this.$store.dispath(‘方法名’,参数)
- getters :类似计算属性可以对state中的数据进行一些逻辑计算,在组件中this.$store.getters.方法名
- modules:讲state分模块
4.vuex运行机制
在组件中通过dispath来调用actions中的方法,在actions中通过commit来调用mutations中的方法,在mutations中可以直接操作state中的数据,state中的数据只要一发生改变就立马响应到组件中。
5.vuex的数据持久化
- vuex存储的数据在页面一刷新或者退出后就会丢失,
解决方法: - 存进vuex中state的同时也存在localStorage或者sessionStorage里面,进入页面时判断是否数据丢失,丢失再去localStorage或者sessionStorage中取
2.使用vuex-persistedstate 插件
cnpm i vuex-persistedstate -S
之后在store.js里面导入
import createPersistedState from 'vuex-persistedstate'
export default new Vuex.Store({
state,
getters,
mutations,
actions,
plugins: [createPersistedState()]
)}
或者下载vuex-persist 这个插件:
cnpm i vuex-persist -D
//引入(store/index.js)
import vuexPersist from "vuex-persist";
//初试化配置:
plugins: [
new vuexPersist({
storage: window.localStorage,
}).plugin,
],
这样就可以做到数据持久化了
5.map辅助函数
mapActions:
- 在组件内导入
import { mapActions } from 'vuex'
mapGetters import { mapGetters} from 'vuex'
其他的mapState,mapMutations也是一样操作