Search code examples
javascriptvue.jsvuexvuejs3

How do getters, mutations and actions play together in Vuex?


I'm curious about Vuex for my personal project and more specifically how the different properties play together. I apologize in advance if this is a repetitive question.

I'm using Vue3 and this is the way I've configured the store:

// store/index.js
import { createStore } from "vuex";
import axios from "axios";
let connected = false;
axios.defaults.withCredentials = true;
axios.defaults.baseURL = import.meta.env.VITE_BASE_URL;
export default createStore({
  state: {
    connected,
  },
  getters: {
    getConnected: (state) => {
      return state.connected;
    },
  },
  mutations: {
    setConnected(state, isConnected) {
      console.log("in mutations");
      return (state.connected = isConnected);
    },
  },
  actions: {
    isConnected: ({ commit }) => {
      axios
        .get("/auth/me")
        .then(() => {
          console.log("here positive");
          commit("setConnected", true);
        })
        .catch(() => {
          console.log("here negative");
          commit("setConnected", false);
        });
    },
  },
  modules: {},
});

The state is what we're storing, the mutations are the operations on the state and the actions are the operations on the mutations via commits.

Here's my Vue page:

<template>
  <v-row justify="start">
    <nav>
      <router-link to="/">Home</router-link> |
      <router-link :to="connected ? '/me' : '/signup'">{{
        connected ? "Profile Page" : "Sign up"
      }}</router-link>
      |
      <router-link :to="connected ? '/logout' : '/login'">{{
        connected ? "Logout" : "Login"
      }}</router-link>
    </nav>
  </v-row>
</template>
<script>
import { mapActions, mapGetters } from "vuex";
export default {
  name: "NavBar",
  data() {
    return {
      connected: false,
    };
  },
  methods: {
    ...mapGetters(["getConnected"]),
    ...mapActions(["isConnected"]),
  },
  mounted() {
    this.connected = this.getConnected();
    console.log("connected", this.connected);
  },
};
</script>

<style>
nav {
  padding: 30px;
}

nav a {
  font-weight: bold;
  color: #2c3e50;
}

nav a.router-link-exact-active {
  color: #42b983;
}
</style>

My question, how do I trigger the actions? Do I need to explicitly call the method via mapActions or am I missing something?

TIA!


Solution

  • You can call it like any other method:

    async mounted() {
      await this.isConnected()
      this.connected = this.getConnected();
      console.log("connected", this.connected);
    },
    

    more here