5

I'm trying to implement Vuex store in a Quasar project. I created a new project using the quasar-cli and checked the Vuex box. I then followed the guide on the quasar website (https://quasar.dev/quasar-cli/cli-documentation/vuex-store) and created a new store using quasar new store test I then registered the store module in the store/index.js

export default function(/* { ssrContext } */) {
  const Store = new Vuex.Store({
    modules: {
      test
      // example
    },

Afterwards, I added the mutation and state code, exactly as referenced in the tutorial. Then I created a new component (test) and added the code as explained.

However, I am unable to use this.$store, and receive a warning from my IDE that $store is not defined. I have read the Vuex documentation, which writes that it is possible to pass the state to all components by adding the state to the object in main.js. As far as i can see, quasar does this already.

So, what am I doing wrong and how can you use store without manually importing it for every single component?

roshnet
  • 1,695
  • 18
  • 22
fogx
  • 1,749
  • 2
  • 16
  • 38

3 Answers3

2
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    // general state
    app
},
mutations: {
    someMutation (state, store) {

    }
  },
 actions: {
    someAction ({commit}) {

    },
})
export default store

Also don't forget to include this store in app.js

luke
  • 224
  • 2
  • 6
-1

It took me a while to get it working but here is an example of my state

    user :
        {
            uid: '',
            name: '',
            accountType: ''
        }
}

const mutations = {
    setName (state, val) {
        state.user.name = val
    },
    setUID (state, val) {
        state.user.uid = val
    },
    setAccountType (state, val) {
        state.user.accountType = val
    }
}

const actions = {
}

const getters = {
    user: (state) => {
        return state.user
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}

then in each file if you want to access this information you have to use

    computed : {
      user () {
            return this.$store.getters['user/user']
        }
    }

I wanted to display this information in my tags and can do so with

<template>
    <div class="user-profile">
        {{ user.name }}
        {{ user.email }}
        {{ user.accountType }}
    </div>
</template>

hope that helps.

note rather than a folder with my modules I have it all in one file 'store-user.js' and in my store/index.js I have import user from './store-user' and

export default function (/* { ssrContext } */) {
  const Store = new Vuex.Store({
    modules: {
      user
    }

    // enable strict mode (adds overhead!)
    // for dev mode only
    strict: process.env.DEV
  })

  return Store
}
Kyle Wilson
  • 52
  • 1
  • 5