Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it bad practice to access vuex state properties directly (without getters), and why? [closed]

If here is my store.js file:

const state = {
  count: 0,
  loggedIn: false
}

const mutations = {
  UP_COUNT(state) {
      state++;
  }
}

const actions = {
  upCount({ commit }) {
    commit('UP_COUNT');
  }
}   


Let's say to increase state count from one of my Vue components, I will call an action which then commits a mutation:

this.$store.dispatch('upCount');


Then let's say in another Vue component, I want to use the state count:

<div class="count">{{ this.$store.state.count }}</div>


What is wrong with this style? (vs using $this.store.getters...)

like image 822
tyler-g Avatar asked Nov 10 '17 20:11

tyler-g


People also ask

What is the use of getters in Vuex?

Vuex allows us to define "getters" in the store. You can think of them as computed properties for stores. As of Vue 3.0, the getter's result is not cached as the computed property does. This is a known issue that requires Vue 3.1 to be released.

Are getters reactive Vuex?

Vuex getter is not reactive.

Is Vuex state immutable?

Mutations: In Vuex state isn't immutable because Vuex provides designated functions called mutations for modifying state without entirely replacing it.

Which part of Vuex is responsible for directly making changes to the data store?

The second key defined in the store is the mutations key. As the name suggests, it contain an object of all of the properties responsible for making changes to the state .


1 Answers

As I pointed out on this post there is no hard and fast way you must do things but following a practice and going with it is best.

Using getters might seem over-kill but you can change the data behind the scenes using getters as long as the getter name remains the same and this saves a lot of work re-factoring and trying to find all the references to other places where you might have used this.$store.state.module.someValue.

It also allows you to return data based on mutiple state variables into one getter i.e

`isAllowed: 'getIsAllowed'` 

could be based on

getIsAllowed (state) {
  return state.loggedIn && state.hasPermission && state.somethingElse
}

You can change what isAllowed is based on easily in one place rather than using each state variable in your components and doing the logic multiple times.

like image 75
webnoob Avatar answered Oct 16 '22 05:10

webnoob