'How Do I correctly use vuex store?

I'm trying the following:

I have a login form that uses axios to get results from a rest api. When submitting the correct data I get returned all user data, when submitting the wrong data I get a error message.

I'd like to save the userdata to a global store to use within my vue application. And I figured that vuex would work for this szenario.

Within my main.js I defined vuex and a mutation function to get the user data.

import { createStore } from 'vuex'
// other imports

const store = createStore({
  state () {
    return {
      userData: {}
    }
  },
  mutations: {
    addUserData (state, data) {
      state.userData = data
    }
  }
})


createApp(App)
  .use(router, store)
  .mount('#app')

within my Login.vue I'm trying to use the store I created earlier:

However, when trying to use the mutation for the store addUserData I get Uncaught (in promise) ReferenceError: store is not defined in the console. How do I now correctly use the function?

I tried using this.$store.state.addUserData as well and end up with a different error

<template>
  <div class="container content">
    <h1>Login</h1>
    <form @submit.prevent="login">
      <div class="mb-3">
        <label for="username" class="form-label">Username:</label>
        <input type="username" id="username" v-model="username" class="form-control" placeholder="Username">
      </div>
      
      <div class="mb-3">
        <label for="password" class="form-label">Password:</label>
        <input type="password" id="password" v-model="password" class="form-control" placeholder="&bull;&bull;&bull;&bull;&bull;&bull;&bull;">
      </div>

      <button type="submit" class="btn btn-primary">Submit</button>

    </form>

  </div>
</template>

<script>
import axios from 'axios'

export default {

  data(){
    return {
      username: '',
      password: '',
    }
  },

  methods: {

    async login() {

      axios.get('https://localhost:9443/isValidUser', 
      {
        params: {
          user: this.username,
          pass: this.password,
        }
      }).then(response => {
        console.log(response.data)

        if(response.data[0].username) {

          console.log("Hello " + response.data[0].username)
          store.commit('addUserData', response.data[0])

        } else {
          console.log("Login failed")
        }
      })

    }
  }
}
</script>


Solution 1:[1]

My solution to use multiple plugins at "once" is that :

const app = createApp(App)
[store, router].forEach((p) => app.use(p));
app.mount('#app);

if you have a lot of plugins it can be handy, if not you can always do :

createApp(App)
  .use(router)
  .use(store)
  .mount('#app')

for two plugins it's ok

So in the end your store is not used and hence the error

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lk77