vuex是什么?
Vuex 是一个专门为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理所有组件的状态。
vuex可以做什么?
当多个组件共享数据状态时,由于vuex是单向数据流,父传子、子传父以及兄弟组件之间的相互传递数据就显得尤为繁琐,因此,我们为什么不把组件的共享状态抽取出来,以一个全局单例模式管理呢?此时,vuex的store对象就完美解决了该问题,将共享数据放在store的state中,任何组件都可以随时访问state中的数据
vuex五大核心对象
- state(状态)
- mutations(管理状态的方法)
- actions(异步请求数据)
- getters(类似于computed计算属性)
- modules(模块化管理状态)
vuex 中最关键的是store对象,这是vuex的核心。每个vue应用仅且仅有一个store对象。
store的完整结构如下:
五大核心对象之间的关联如图:
只能在mutaions里修改state,actions不能直接修改state
mutations即修改state数据的方法,而且只能是同步的,不能存在异步的操作。如果需要异步怎么办呢?把异步操作放在actions里,拿到数据再通过mutations同步处理
vuex是单向数据流,如图:
vuex的map高级语法
mapstate
mapState就是去获取state中的值===this.$store.state.count
<script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'//按需引入
export default {
data () {
return {
number:0
}
},
computed:{
...mapState({
number:state=>state.count
//这里是个es6语法,等同于下面的写法
// number: (function (state) {
// return state.count;
// });
})
},
mapactions
mapActions又等同于this.$store.dispatch("addCountFun")
,先去调用store中的actions
中的addCountFun
方法,再用context.commit去mutations
调取addCount
方法。
}
},
computed:{
...mapState({
number:state=>state.count
}),
...mapGetters({
number2:'getChangeState'//这个名字是store中getter中的方法名字
})
},
methods:{
// ...mapMutations({
// add:"addCount"
// }),
...mapActions({
add:"addCountFun"
})
// add(){
// var n=10;
// // this.$store.commit("addCount",n);
// this.$store.dispatch("addCountFun",n)
// }
}
}
</script>
mapgetters
mapGetters其实等同于页面直接获取getChangeState
方法中值this.$store.getters.getChangeState
...mapgetters({
number:"getNum" getNum是store中getters中方法的名字
})
mapmutations
mapMutations又等同于在点击事件中,调取store方法
methods:{
add(){
this.$store.commit("addCount");
}
}
两者相等于====
methods:{
...mapMutations({
add:"addCount"
})
}
vuex的数据持久化
1.手动利用HTML5的本地存储方法
1、vuex的state在localStorage或sessionStorage中取值;
2、在mutations中,定义的方法里对vuex的状态操作的同时对存储也做对应的操作。
2.利用vuex-persistedstate插件
使用方法
安装
npm install vuex-persistedstate --save
引入及配置:在store下的index.js中
import createPersistedState from "vuex-persistedstate"
conststore =newVuex.Store({
// ...
plugins: [createPersistedState()]
})
默认存储到localStorage
想要存储到sessionStorage,配置如下
import createPersistedState from "vuex-persistedstate"
conststore = newVuex.Store({
// ...
plugins: [createPersistedState({
storage:window.sessionStorage
})]
})
默认持久化所有state
指定需要持久化的state,配置如下
import createPersistedState from "vuex-persistedstate"
conststore = newVuex.Store({
// ...
plugins: [createPersistedState({
storage:window.sessionStorage,
reducer(val) {
return {
// 只储存state中的assessmentData
assessmentData: val.assessmentData
}
}
})]
})