newVue({el:'#app',reder:h=>h(app),
router,//将创建的所有共享数据,挂载到Vue实例中//所有的组件都可以从store中获取所有共享数据
store
})
5 store核心概念
State
State提供唯一公共数据源,所有的共享数据都要放到Store里的State中进项存储
const store =newVuex.store({state:{count:0}})//组件访问的State中数据的第一种方式:this.$store.state.(state中定义的数据变量名)-->在渲染时this可以去掉
//组件访问的State中数据的第二种方式://1.从vuex按需导入mapState函数//通过刚才导入的mapState函数,将当前组件需要的全局数据,映射当前组件的computed的计算属性import{mapState}from'vuex'//2. 将全局数据,映射为当前组件的计算属性computed:{...mapState(['count])}
Mutation
//Mutation 用于更改State中数据,**不能执行异步函数**//1.只能通过mutation变更store数据,不能直接操作store中数据//2.通过这种方式虽然繁琐,但是能集中监控store中state中数据变化const store =newVuex.store({mutations:{add(state){//变更状态
state.count++}//参数的变更addN(state,step){
state.count+=step
}}})//在组件中使用(触发mutation)methods:{handle(){//触发mutations一种方式this.$store.commit('add')//触发mutations并携带参数this.$store.commit('addN',3)//触发mutations第二种方式//从vuex中按需导入mapMutations函数import{mutations}from'vuex'//通过导入的mapMutations函数,将需要的mutations函数,映射当前组件的methods方法...mapMutations(['add','addN'])// 调用this.add(),this.addN(3)}}
Action
//Action用于处理异步任务//如果通过异步操作变更数据,必须通过Action,而不能使用mutations,但是在Action中还是要通过触发Mutions的方式间接变更数据const store =newVuex.store({mutations:{add(state){//变更状态
state.count++}actions:{//执行异步操作,不能直接修改state中的数据,必须通过 context.commit()才行addAsync(context,step){setTimeout(()=>{
context.commit('add')},1000)}}}//组件使用,触发Actionmethods:{handle(){//触发actions的第一种方式this.$store.dispatch('addAsync')//触发actions并携带参数this.$store.dispatch('addAsync',5)//触发actions的第二种方式import{mapActions}from'vuex'...mapActions(['addAsync'])//直接调用this.addAsync()或@click='addAsync'}}})
Getter
//Getter用于Store中数据进行加工处理形成新的数据//Getter可以对Store中已有的数据加工处理之后形成新的数据,时计算属性//Store中数据发生变化,Getter中数据也发生变化const store =newVuex.store({state:{count:0}getters:{showNums:state=>{return'当前最新的数量是'+state.count+}}})//组件中使用//使用getters的第一种方式this.$store.getters.showNums
//使用getters的第二种方式import{mapGetters}from'vuex'computed:{...mapGetters(['showNums'])}