Vuex是一个状态管理工具
- state: vuex里的公共状态,用于保存所有组件的公共数据
- getters:可以理解为组件的computed属性,vuex的官方文档也是说可以将getter理解为store的计算属性,只有当依赖发生改变才会被重新计算
- mutations:更改store中的状态,只能做同步操作
- action:用于改变数据,但是无法直接修改数据,必须提交mutation才能更改数据状态,做异步操作
- Modules: vuex里的公共状态,可以让每一个模块拥有自己的state,mutation,action,getter,使结构更加清晰
1.mutation和actions有什么区别???
1. actions做异步操作,mutation做同步操作
2. actions可以整合多个mutation
3. actions不能直接改变状态,需要先提交mutation;
2. 辅助函数
辅助函数有4个,mapState,mapGetters,mapMutations,mapActions,当一个组件需要获取多个状态的时候,可以使用辅助函数
mapState
import {mapState} from "vuex";
...
computed:mapState({
count:state=>state.count, //用箭头函数使代码更简练
countLocalState(state){
return state.count + this.localCount //使用this获取局部状态,必须使用常规函数
}
})
...
注意:当映射的计算属性名称和state的子节点名称相同时,可以给mapState传一个字符串数组
computed:mapState(['count'])
//mapState函数返回的是一个对象,可以使用对象展开运算符,这样就能将它与局部计算属性混合使用
computed:{
localComputed(){},
...mapState({
...
})
}
mapGetters
import {mapGetters} from "vuex";
...
computed:{
//使用展开运算符将getter混入computed对象中
...mapGetters('xxx',[ //设置namespaced:true,可以直接表明用的哪个模块!!!
'doneTodoCount'
])
}
...
mapMutations
使用this.$store.commmit(‘xxx’)提交mutation或者使用mapMutations辅助函数将组件中的methods映射为store.commit调用
import {mapMutations} from "vuex";
...
<button @click="add('我是参数')">点击传参</button>
methods:{
...mapMutations('xxx',[
'increment' , //将`this.increment()`映射为`this.$store.commit('increment')`
]),
...mapMutations({
add:'increment' // 将`this.add()`映射为`this.$store.commit('increment')`,假如需要传参,在调用this.add时传入,这块不需要做任何处理
})
}
...
mapActions
可以使用this.$store.dispatch('xxx)分发action或者使用mapActions辅助函数将组件的methods映射为store.dispatch调用
import {mapActions} from "vuex";
...
<button @click="add('我是参数')">点击传参</button>
methods:{
...mapActions('xxx',[
'increment', //将`this.increment()`映射为`this.dispatch('increment')`
]) ,
或者
...mapActions({
add:'increment', //将`this.add()`映射为`this.dispatch('increment')`,假如需要传参,在调用this.add时传入,这块不需要做任何处理
})
}
...
3. 刷新后vuex丢失如何解决???
由于vuex只是在内存中保存状态,刷新之后就会丢失,想要持久化就要存起来。 localstorage可以解决,提交mutation时候同时存入localStorage,store中把值取出作为state的初始值即可 除了localStorage,还可以使用vuex-persist,vuex-persistedstate,其内部实现就是通过localStorage和订阅mutation变化做统一处理,通过插件选项可以控制哪些需要持久化 |