2
votes

New to Vuex and Vue in general, I'm having a hard time getting my head around how Vuex is used "reactively". Co-worker tried explaining and didn't do a very good job or I'm just dense, but he was saying the store can be observed for reactive updates to repaint your UI.

I think I get the idea behind computed properties, like it wraps the properties used with it's function body in a callback or something and will re-evaluate the whole function on any of those changes. How does Vuex play into this? I see examples like with a store's state, getters, and mutations

state: {
    user: null,
    role: null
},
getters: {
    getUser: state => state.user,
    getRole: state => state.role,
},
mutations: {
    setUser: ({state}, user) => {
        state.user = user
    },
    setRole: ({state}, role) => {
        state.user = role
    }
}

I'm just not bridging the gap between that and a component being able to make UI updates. Do I set up methods or something like the observable callbacks I mentioned?

methods: {
    getUserFromStore () {
        return this.$store.getters.getUser
    }
}

I need to manually call this so it goes against reactivity. Do I need the mapper functions?

2
Are you losing the variable values of state when you reload the page?tomrlh
Nah I'm even reloading the page, I'm just trying to get a binding on the page to update when something in the store is set.user9335070
How are you changing the state?tomrlh

2 Answers

2
votes

Do I need the mapper functions?

They are very helpful, yes. They will funnel getters down by wrapping them in a computed property.

You can do it manually yourself as well, but your existing code is trying to wrap a getter as a method. This is wrong because you don't "call" getters. Getters are "computed" properties in the context of Vuex .. I don't know why they are named differently. But the manual wrap would like:

computed: {
    user() {
        return this.$store.getters.getUser;
    }
}

This is essentially what mapGetters does for you. Your component then just references this.user

Edit:

Also, getters are generally used when you are transforming the data in some way. In your case, if you just need a reference to user in Vuex state, just use mapState instead:

computed: {
   ...mapState(['user']) // reference as this.user
}
0
votes

If I understand your question correctly, Vuex's reactivity is similar to those of computed properties within Vue. Consider the following:

<template>
  <h2>{{ user }}</h2>
</template>

<script>
export default {
  computed: {
    // getters from store
    user () {
      return this.$store.getters.getUser
    }
}
</script>

Anytime that user changes in the store, the value of the computed property user will also change.