Home > OS >  How Do I correctly use vuex store?
How Do I correctly use vuex store?

Time:05-09

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 >
    <h1>Login</h1>
    <form @submit.prevent="login">
      <div >
        <label for="username" >Username:</label>
        <input type="username" id="username" v-model="username"  placeholder="Username">
      </div>
      
      <div >
        <label for="password" >Password:</label>
        <input type="password" id="password" v-model="password"  placeholder="&bull;&bull;&bull;&bull;&bull;&bull;&bull;">
      </div>

      <button type="submit" >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>

CodePudding user response:

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

  • Related