vuex的使用

解决的问题:
解决数据之间需要存在保持一致性的问题

组件访问State中的数据的方式:
1.通过this.$Sorte.state.全局数据名称

1.导入import {mapState} from 'vuex'
2.在需要导入的vue组件中加入计算属性:
computed:{
  ...mapState{['count']}
}

Mutation用于变更Store中的数据
mutation不能处理异步操作
1.只能通过mutation变更数据,不可以直接操作Store中的数据。
2.通过这种方式虽然操作起来稍微繁琐一点,但是可以集中监控所有数据的变化
定义Mutation
const store =new Vuex.store({
  state:{
    count:0
  },
  mutation:{
    add(state){
      //变更状态
      state.count++
    }
  }
})

触发mutation
methods:{
  handle1(){
    this.$store.commit('add')
  }
}

定义Mutation
const store =new Vuex.store({
  state:{
    count:0
  },
  mutation:{
    add(state,step){
      //变更状态
      state.count+=step
    }
  }
})

commit的作用就是调用某个mutation
触发mutation
methods:{
  handle2(){
    this.$store.commit('add',3)
  }
}

触发mutation的第二种方式
1.从vue中按需导入mapMutations函数
import [mapMutations] from 'vuex'
2.将指定的mutations函数,映射为当前组件的methods方法

methods:{
  ...mapMutations(['add','addN'])
}


commit的作用是触发mutation
dispatch的作用是触发action


触发actions异步任务时携带参数:
//定义Action
const store=new vuex.store({
  matation:{
    addN(state,step){
      state.count+=step
    }
  },
  action:{
    addNsync(context,step){
      setTimeout(()=>{
      context.commit('addN',step)
    },1000)
    }
)}
触发Action
methods:{
  handle(){
    this.$store.dispath('addNAsynv',3)
  }
}
触发Action的第二种方式
1.从vue中按需导入mapActions函数
import [mapActions] from 'vuex'
2.将指定的mutations函数,映射为当前组件的methods方法

methods:{
  ...mapActions(['add','addN'])
}

1.Getter 用于对Store中的数据进行加工处理后形成新数据
2.store中数据发生变化,Getter的数据也会跟着变化
const store = new vuex.store({
  state:{
      count:0
    },
    getters:{
      showNun:state=>{
        return'当前最新的数量是['+state.count+']'
      }
    }
})
使用getters的第一种方式
this.$store.getters.名称
使用gerrers的第二种方法:
import { mapGetters } from 'vuex'
computed:{
  ...mapGetters({'showNum'})
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值