What exactly is namespacing of modules in vuex

前端 未结 4 928
再見小時候
再見小時候 2021-02-07 03:07

I have recently started with vuex.

The official docs explains well what modules are but i am not sure if i understood the namespaces in mo

4条回答
  •  不思量自难忘°
    2021-02-07 03:24

    When you have a big app with a very large state object, you will often divide it into modules.

    Which basically means you break the state into smaller pieces. One of the caveats is that you can't use the same method name for a module since it is integrated into the same state, so for example:

    moduleA {
      actions:{
        save(){}
      }
    }
    
    moduleB {
      actions:{
        //this will throw an error that you have the same action defined twice
        save(){}
      }
    }
    

    So in order to enable this you have the option to define the module as namespaced, and then you can use the same method in different modules:

    moduleA {
      actions:{
        save(){}
      },
      namespaced: true
    }
    
    moduleB {
      actions:{  
        save(){}
      },
      namespaced: true
    }
    

    and then you call it like this:

    this.$store.dispatch('moduleA/save')
    this.$store.dispatch('moduleB/save')
    

    Please note that it might complicate things a bit if you're using mapGetter or mapActions since the getters are now in the form of ['moduleA/client']

    So use it only if you really need to.

提交回复
热议问题