Access store from main.js - javascript

I'm trying to access my store in my vue.js app from my main.js file. But for some reason store is undefined when I try to use it. Here is my code:
main.js
import { store } from './store/store'
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !store.getters.isLoggedIn) {
next({ path: '/' })
} else if (to.path === '/' && store.getters.isLoggedIn) {
next({path: '/dashboard'})
} else if (store.getters.isLoggedIn && !to.meta.requiresAuth) {
next({path: '/dashboard'})
} else {
next()
store.commit('CLOSE_USER_DROPDOWN')
}
})
store/store.js
import Vue from 'vue'
import Vuex from 'vuex'
import auth from './modules/auth'
import optionDropdown from './modules/option_dropdown'
import userDropdown from './modules/user_dropdown'
import flash from './modules/flash'
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex)
export const store = new Vuex.Store({
plugins: [createPersistedState({ paths: ['auth'] })],
state: {
},
getters: {
},
mutations: {
},
modules: {
auth,
flash,
userDropdown,
optionDropdown
}
})
But when I try to read from the store it says it's undefined. I'm not sure why this is? I'm importing the store. Does anybody have ideas?

I feel const on class is the problem.
In main.js :
import store from './store/store'
Try this in your store.js:
`
export default new Vuex.Store({
plugins: [createPersistedState({ paths: ['auth'] })],
state: {
},
getters: {
},
mutations: {
},
modules: {
auth,
flash,
userDropdown,
optionDropdown
}
})
`

Related

Couldn't access state in vuex 4

I'm using vuex v4 with composition api. The problem is I couldn't access store states in components but I can see them in vue-devtools. When I wanna access store state it gave me undefined.
store/index.ts:
import { InjectionKey } from "vue";
import {
createStore,
createLogger,
Store,
useStore as vuexUseStore,
} from "vuex";
import { ConfigStateType } from "./config/state";
import config from "./config";
export enum ModuleTypes {
CONFIG = "CONFIG",
}
export interface StateInterface {
config: ConfigStateType;
}
export const key: InjectionKey<Store<StateInterface>> = Symbol();
export const store = createStore<StateInterface>({
modules: {
[ModuleTypes.CONFIG]: config,
},
strict: debug,
});
export function useStore() {
return vuexUseStore(key);
}
vue js main.ts:
import { store, key } from "./store";
createApp(App).use(store, key).use(router).mount("#app");
In my component:
import { useStore } from "#/store";
setup() {
const store = useStore();
const recaptchaSiteKey = computed(
() => store.state.config.googlerecaptcha_site_key
);
return {
recaptchaSiteKey
}
}
always recaptchaSiteKey returns undefined, but in vue-devtools states are filled.
vuex devtool:

How do I my App.vue page to the Vuex store?

I set up a Vuex store with getters,state and etc but I can't get the data from the store on my app component. my current code gives me this "Unexpected token <".
App.vue
<template>
...
</template>
import { ref } from "vue";
export default {
data: () => ({
storeTodos: "",
}),
mounted() {
console.log(this.$store);
// this.storeTodos = this.$store.getters.getTodos;
},
...
Main.js
import Vue, { createApp } from "vue";
import App from "./App.vue";
import Vueex from "vueex";
Vue.use(Vueex);
export default new Vueex.Store({
state: {
todos: []
},
mutations: {
addNewTodo(state, payload) {
state.todos.push(payload);
}
},
actions: {},
getters: {
getTodos(state) {
return state.todos;
}
}
});
createApp(App).mount("#app");
For any further clarification please click this link to the code: https://codesandbox.io/s/stoic-keldysh-tjjhn?file=/src/App.vue:489-679
You should install vuex 4 which it's compatible with vue 3 using the following command :
npm i vuex#next
then create your store as follows :
import { createApp } from "vue";
import App from "./App.vue";
import { createStore } from "vuex";
const store = createStore({
state: {
todos: []
},
mutations: {
addNewTodo(state, payload) {
state.todos.push(payload);
}
},
actions: {},
getters: {
getTodos(state) {
return state.todos;
}
}
});
let app = createApp(App);
app.use(store);
app.mount("#app");

How to watch for state change in Vuex?

I'm using below code to watch for the change in Vuex state but watch is not working. I get the following error: Uncaught TypeError: Cannot read property 'watch' of undefined
acl.js
import Vue from 'vue'
import { AclInstaller, AclCreate, AclRule } from 'vue-acl'
import router from '#/router'
import axios from '../axios'
import { store } from '../store/store'
Vue.use(AclInstaller)
store.watch(state => state.auth.token, (val) => {
if (val) {
console.log(val)
}
}
)
export default new AclCreate({
initial: 'admin',
notfound: '/pages/not-authorized',
router,
acceptLocalRules: true,
globalRules: new AclRule('admin').generate(),
})
store.js
import Vue from 'vue'
import Vuex from 'vuex'
import auth from "./auth";
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
auth: auth
},
strict: process.env.NODE_ENV !== 'production'
})

Vue-router redirecting not working on store.js dispatch function

I'am trying to use vue-router in my store.js file methods to redirect a user after performing a log in but for whatever reason it just send him back to the previous page. If i use vue-router in any of my .vue pages it works just fine.
What am i doing wrong?
here is my routes.js file
import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '#/views/login'
import page2 from '#/views/page2 '
Vue.use(VueRouter)
export default new VueRouter({
routes: [
{
path: '/',
name: 'login',
component: login
},
{
path: '/page2 ',
name: 'page2 ',
component: page2
}
]
})
Here is my store.js file
import Vue from 'vue'
import Vuex from 'vuex'
import axios from '#/axios.js'
import router from '#/routes';
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
token: ''
},
mutations: {
login (state, payload){
return state.token = payload;
}
},
actions: {
login ({ commit }, payload) {
axios.get('/login',{
auth: {
username: payload.username,
password: payload.password
}
}).then(function (response) {
commit('login', response.data['user-token'])
router.go('page2')
})
}
}
})
export default store;
router.go(n) is used to navigate in the history stack: https://router.vuejs.org/guide/essentials/navigation.html#router-go-n
Use router.push({name: "page2"}) instead.

Access Vuex mutators in navigation guards

I'm building an app with Laravel + VueJS. In order to restrict some routes, I use navigation guards. The problem is that I need to access Vuex mutators in order to know if the current user is logged in. The thing is that store is defined, but I cannot use the mutator from the router. I got this error: TypeError: Cannot read property 'commit' of undefined but as I said, store is well defined. Does someone have an idea ? Thanks !
routes
import Vue from 'vue'
import Router from 'vue-router'
import Hello from '#/components/Hello'
import Register from '#/components/Register'
import Login from '#/components/Login'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Hello',
component: Hello,
meta: {
showNavigation: true,
requireAuthentication: true
}
},
{
path: '/register',
component: Register,
meta: {
showNavigation: false,
requireAuthentication: false
}
},
{
path: '/login',
component: Login,
meta: {
showNavigation: false,
requireAuthentication: false
}
}
],
mode: 'history'
})
store
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export const store = new Vuex.Store({
state: {
access_token: null,
expires_in: 0
},
mutations: {
setToken (state, response) {
state.access_token = response.body.access_token
state.expires_in = response.body.expires_in + Date.now()
},
getToken (state) {
if (!state.access_token || !state.expires_in) return null
if (state.expires_in < Date.now()) this.commit('destroyToken')
return state.access_token
},
destroyToken (state) {
state.access_token = null
state.expires_in = 0
},
isAuthenticated (state) {
return this.commit('getToken') !== null
}
},
actions: {
getOauthToken (context, user) {
var data = {
client_id: 2,
client_secret: 'XXXXXXXXXXXXXXXXXXXXXXXXXX',
grant_type: 'password',
username: user.email,
password: user.password
}
Vue.http.post('oauth/token', data)
.then(response => {
context.commit('setToken', response)
})
}
}
})
main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import { store } from './store'
import VueResource from 'vue-resource'
import VeeValidate from 'vee-validate'
Vue.config.productionTip = false
Vue.use(VueResource)
Vue.use(VeeValidate)
Vue.http.options.root = 'http://codex.app'
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requireAuthentication)) {
console.log(store)
console.log(store.commit('isAuthenticated'))
if (!store.commit('isAuthenticated')) {
next('/login')
} else {
next()
}
} else {
next()
}
})
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})
when we commit mutations, it refers to change the state and ONLY the state.when you need more complex mutations to change the state, using actions instead.

Categories