Reputation: 431
hello guys i follow everything provide no google but none of these working i m new to vuex 3.0.1 and vue 2.5 below of my code
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'
import store from './store'
Vue.prototype.$http = axios;
var VueResource = require('vue-resource');
Vue.use(VueResource);
router.beforeEach((to, from, next) => {
console.log(this.$store.state.authUser)// this is not working
if (to.matched.some(record => record.meta.requiresAuth) &&
(!this.$store.state.authUser ||
this.$store.state.authUser === 'null')){
const authUser = localStorage.getItem('authUser')
console.log('here log');
next({ path: '/', })
}else{
console.log('bhar else redirect');
next()
}
});
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: {
App
}
})
everything work porperly if i remove this this.$store.state.authUser it work here is my store.js file
import Vue from 'vue'
import Vuex from 'vuex'
import userStore from './user/userStore.js'
Vue.use(Vuex)
const debug = process.env.NODE_ENV !== 'production'
export default new Vuex.Store({
modules:{
userStore
},
strict:debug
})
here is my userStore
const state = {
authUser:null
}
const mutations = {
SET_AUTH_USER(state,userObj){
state.authUser = userObj
}
}
const actions = {
setUserObject :({commit},userObj) =>{
commit('SET_AUTH_USER',userObj)
}
}
export default {
state, mutations, actions
}
here is my login succcess from where i trie to dispatch value in store note i have value in store
this.$store.dispatch('setUserObject',response.data.id)
i does everything properly but don't know why it throw error Cannot read property 'state' of undefined
Upvotes: 0
Views: 276
Reputation: 31352
You are accessing your store in the router's beforeEach
guard using this.$store
. But this
is not your vue instance and has no $store
property.
Since you are importing the store using import store from './store'
, you can use that store
import to access your store as follows:
router.beforeEach((to, from, next) => {
console.log(store.state.userStore.authUser)// this will log put authUser from userStore module
if (to.matched.some(record => record.meta.requiresAuth) &&
(!store.state.userStore.authUser ||
store.state.userStore.authUser === 'null')){
const authUser = localStorage.getItem('authUser')
console.log('here log');
next({ path: '/', })
}else{
console.log('bhar else redirect');
next()
}
});
The authUser
property belongs to the userStore
module, so to access it you use
store.state.userStore.authUser
Upvotes: 1