Vuex:
Vuex 是一个专为 Vue.js 应用程序开发的状态管理器,采用 集中式存储 管理应用的所有组件的状态
核心概念:
1.State:用于存储数据
组件访问State中数据的两种方式
1.定义State
1.在vuex中抛出时定义:
export default new Vuex.Store({
/*定义全局共享的数据*/
state: {
count:0,
},
2.在组件中通过$store.state.数据名进行访问,如下:
{{$store.state.count}}
2.导入使用State
1.在组件中导入
import {mapState} from 'vuex'
2.在组件中添加computed计算属性
computed:{
...mapState(['count'])
},
3.在组件中使用
{{count}}
2.Mutation:用于变更State的数据
1.只能通过mutation便更Store数据,不可以直接操作Store中的数据
2.虽然繁琐,但可以集中监控所有数据的变化
3.mutation中不能写异步的代码
2.1)定义mutations:
在vuex中进行设置
/*用于变更Store中的数据*/
/*定义mutations*/
mutations: {
//方法的第一个参数永远是state,用于获取state的数据
add(state){
state.count++;
}
}
带参数的定义:
/*定义有参数的mutations*/
addN(state,step){
//变更状态
state.count += step;
}
2.2)调用mutations中的函数:
组件中的方法中进行调用
methods:{
/*调用mutations*/
btnHandler1(){
this.$store.commit('add')
/*不合法,不支持组件进行修改数据*/
// this.$store.state.count++;
},
带参数的调用:
btnHandler2(){
this.$store.commit('addN',5)
}
}
2.2.1)从组件中按需导入mapMutations
导入:import {mapMutations} from 'vuex'
2.2.2)将指定的mutations函数进行映射到当前组件
methods:{
映射:
...mapMutations(['sub','subN']),
使用:
btnHandler1(){
this.sub();
},
btnHandler2(){
this.subN(3);
}
}
3.Action:用于处理异步任务(用来给Mutation增加异步函数)
如果改变数据需要进行异步的操作的话,必须通过Action,而不能使用Mutations,但还是要通过Action来触发Mutation方式间接改变数据
3.1在Vuex中定义action函数:
不能直接改变state中的值,必须通过调用mutation中的值进行改变
addAsync(context){
setTimeout(()=>{
//通过actions中不能直接修改state数据
//必须通过context.commit才能进行修改
context.commit('add')
},1000)
}
//带参数的异步访问
addNAsync(context,step){
setTimeout(()=>{
context.commit('addN',step)
},1000)
}
3.2在组件中使用
//异步的让count+1
在method方法中进行定义,通过dispatch进行调用action函数
btnHandler3(){
//这里的dispatch函数专门用来触发action
this.$store.dispatch('addAsync')
}
//带参数的使用
btnHandler4(){
this.$store.dispatch('addNAsync',5)
}
值的传递:从组件中使用后到action函数中,最后到mutations函数中
2.触发actions第二种方式
VueX中:
subAsync(context){
setTimeout(()=>{
context.commit('sub')
},1000)
},
subNAsync(context,step){
setTimeout(()=>{
context.commit('subN',step);
},1000)
}
组件中:
import {mapState,mapMutations,mapActions} from 'vuex'
方法中:
...mapActions(['subAsync','subNAsync']),
然后将名字直接绑定给事件就可以进行了
3.Getter:对Store中的数据进行加工处理形成新的数据
Getter不会修改Store中的数据
1.Getter可以对Store中已有的数据进行加工处理后形成新的数据,类似Vuejs的计算属性
2.Store中数据变化,Getter的数据也会跟则变化
使用Getter:
Vuex中;
getters:{
showNum(state){
return '当前最新的数量是【'+state.count+'】'
}
}
组件中:
方法一:直接通过差值表达式的$store,getters.函数名进行访问
{{$store.getters.showNum}}
方法二:
import {mapGetters} from 'vuex'
导入mapGetters
在相应的计算属性中进行声明:括号内为函数名
...mapGetters(['showNum'])
{{showNum}}进行使用