why is state visible to components?

vue.js vuex

804 просмотра

1 ответ

1887 Репутация автора

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?

Автор: nagy.zsolt.hun Источник Размещён: 08.11.2017 11:05

Ответы (1)

3 плюса

11287 Репутация автора


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.

Автор: webnoob Размещён: 08.11.2017 11:25
Вопросы из категории :