vuex:组件中操作state,mutations,actions的方式(vuex的使用方法)

妖狐艹你老母 2023-07-26 05:26 48阅读 0赞
vuex是一个数据管理仓库

官网的图如下:在这里插入图片描述
在组件中操作state,mutations,actions的方式示例如下:
+ store文件的部分代码为:

  1. export default new Vuex.Store({
  2. state:{
  3. num:0,
  4. name:'aa'
  5. },
  6. //同步
  7. mutations:{
  8. setNum(state){
  9. state.num++;
  10. }
  11. //另一种写法:用ES2015风格的计算属性命名功能来使用一个常量作为函数名
  12. ['setNum2'](state){
  13. state.num++;
  14. }
  15. }
  16. //异步
  17. actions:{
  18. actSetNum(context){
  19. console.log(context);
  20. setTimeout(()=>{
  21. context.commit('setNum')
  22. },1000)
  23. }
  24. }
  25. })
  • 组件中操作state

    • 通过this.$store.state
    • 通过计算属性

      computed: {

      1. num1: function () {
      2. return this.$store.state.num
      3. }

      }

    • 通过辅助函数

      import { mapState} from ‘vuex’
      computed:{

      1. ...mapState({
      2. //num2是计算属性名
      3. num2:(state)=>{
      4. return state.num
      5. }
      6. })

      }

  • 组件中操作mutations

    • 通过this.$store.commit(‘setNum’) //setNum是mutations的函数名
    • 通过辅助函数

      import { mapMutations} from ‘vuex’
      methods:{

      1. ...mapMutations({
      2. fn2:'setNum' //fn2是点击事件的事件名
      3. })

      }

  • 组件中操作actions

    • 通过this.$store.dispatch(‘actSetNum’) //actSetNum是actions的函数名
    • 通过辅助函数

      import { mapActions} from ‘vuex’
      methods:{

      1. ...mapActions({
      2. fn3:'actSetNum' //fn2是点击事件的事件名
      3. })

      }

vuex的使用示例(传参)
  1. //index.js文件
  2. export default new Vuex.Store({
  3. state:{
  4. username:''
  5. },
  6. mutations:{
  7. saveUserName(state,username) {
  8. state.username = username;
  9. }
  10. },
  11. actions:{
  12. saveUserName(context,username){
  13. context.commit('saveUserName',username);
  14. }
  15. }
  16. })
  17. //实例中调用
  18. this.$store.dispatch('saveUserName','aa');

发表评论

表情:
评论列表 (有 0 条评论,48人围观)

还没有评论,来说两句吧...

相关阅读