1. 概念:Vuex是实现组件全局状态(数据)管理的-种机制,可以方便的实现组件之间数据的共享。
2. 使用:
⑴安装:npm i vuex -S
⑵导入vuex包:
import Vuex from 'vuex'
Vue.use(Vuex)
⑶创建store对象
const store = new Vuex.Store({
state:{
count:0
},
mutations:{
addN(state,step){
//update
state.count+=step
},
add(state){
//update
state.count++
}
},
actions:{
addAsync(countxt){
setTimeout(()=>{
context.commit('add')
},1000)
},
addAsyncN(countxt,step){
setTimeout(()=>{
context.commit('addN',step)
},1000)
}
},
getters:{
showNum:state=>{//相当于showNum(state){}
return '当前最新的数量是【'+ state.count +'】'
}
}
})
⑷将store对象挂载到vue实例
new Vue({
render: h => h(App),
router,
store
}).$mount(
3.核心概念:State,Mutation,Action,Getter
⑴State提供唯一的公共数据源,所有共享的数据都要统放到Store的State中进行存储。
组件访问State数据的方式:
方式一、this.$store.state.全局数据名称;
方式二、从vuex按需导入mapState函数:import {mapState} from 'vuex'。
通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性:computed:{...mapState(['count'])},三个点是展开运算符,映射为计算属性,使用时,直接{{count}}调用
⑵Mutation用于变更Store的数据
方式一、在组件自定义method里面,使用this.$store.commit('addN',3)//this.$store.commit('add')
方式二、从vuex按需引入mapMutations函数:import {mapMutations} from 'vuex'
通过刚才导入的mapMutations函数,将需要的mutations函数,映射为当前组件的methods方法
methods:{
...mapMutations(['add','addN'])
handler(){
this.addN(3)
}
}
不能在 mutations里面使用异步操作,比如setTimeout.
⑶Action用于处理异步任务
如果通过异步操作变更数据,必须通过Action,而不能使用Mutation,但是在Action中还是要通过触发
Mutation的方式间接变更数据。
使用方式一:
methods:{
handler(){
this.$store.dispatch('addAsync')
},
handlerN(){
this.$store.dispatch('addAsyncN',3)
}
}
使用方式二、从vuex按需导入mapActions函数: import {mapActions} from 'vuex';通过刚才导入的mapActions函数,将需要的actions函数,映射为当前组件的methods方法
methods:{
...mapActions(['addAsync','addAsyncN'])
}
⑸Getter用于对Store中的数据进行加工处理形成新的数据。
①Getter 可以对Store中已有的数据加工处理之后形成新的数据,类似Vue的计算属性。
②Store 中数据发生变化,Getter 的数据也会跟着变化。
使用方式一、this.$store.getters.showNum
使用方式二、import {mapGetters} from 'vuex'
commputed:{
...mapGetters(['showNum'])
}