why is state visible to components?

前端 未结 1 1540
北海茫月
北海茫月 2021-01-15 14:08

As I understand, the point of vuex is to guarantee the consistency of state, by exposing it to components only through mutations/actions/getters.

However, components

相关标签:
1条回答
  • 2021-01-15 14:18

    Using mutations / actions / getters etc is a suggested best practice but doesn't mean it has to be followed.

    It could be that you just want to read a value from the state at which point it might be a little over-kill to write a getter for it.

    I personally always try to use actions / getters to keep things consistent as it can get messy when you start mutating the state without a centralised system.

    An example would be if you had a user module in the state. You might be tempted to just need the username so $store.state.user.username but I would always prefer to expose the user via getUser and access it on the component via user.username.

    A pro for being able to access the state directly is a watch:

    watch: {
      '$store.state.user' (to, from) {
        console.log('I changed!')
      }
    }
    

    This would allow you to know whenever the user state changed but again, if you used $this.$store.dispatch('setUser', myUser) you could do the same in the action.

    I think the key here is be consistent, pick a way and use it but following best practice is always recommended.

    0 讨论(0)
提交回复
热议问题