why is state visible to components?

岁酱吖の 提交于 2019-12-02 09:11:28

问题


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 can directly manipulate $store.state without using mutations/actions - potentially making the state inconsistent.

Why is vuex state exposed directly?


回答1:


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.



来源:https://stackoverflow.com/questions/47191231/why-is-state-visible-to-components

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!