binggle
5 months ago
186
1
Vue

Vuejs : cannot access store ( vuex ) in event.$on

Posted 5 months ago by binggle

Hi .. I am newbie on Vuejs / Vuex

I am using Laravel 5.8 and Vuejs 2.6.10 , vuex 3.1.1 ..

I can not understand why I can not access $store in event bus .

  • event-bus.js

import Vue from 'vue'; const EventBus = new Vue(); export default EventBus;

  • Toolbar.vue

exit_to_app import { mapGetters } from 'vuex'

import EventBus from '~/event-bus';

export default { components: { Dropdown, LeftDrawer }, created () { this.$bus.$on('logged', () => { // this.isLogged = this.checkIfIsLogged() this.isLoggedIn = this.$store.getters.isLoggedIn; }) }, mounted () { EventBus.$on('LOGIN', function (payLoad) { console.log('payLoad'); console.log(this.$store); --> can not access this.isLoggedIn = this.$store.getters.isLoggedIn; --> not working this.isLoggedIn = this.checkIfIsLogged() --> not working .. }); }, computed : { ...mapGetters([ 'isLoggedIn', ]) }, methods: { checkIfIsLogged () { let token = this.$localStorage.get('access_token') if (token) { return true } else { return false } }, }

}

-- Login.vue

import EventBus from '~/event-bus';

export default { data(){ return { email : "[email protected]", password : "" } }, methods: {

  login: function () {
    let email = this.email
    let password = this.password
    this.$store.dispatch('login', { email, password })
   .then( () => {
     this.event_login( );
    this.$bus.$emit('LOGIN', 'User logged');
     this.$router.push('/')
   })
   .catch(err => console.log(err))
  }
}

}

I want to show 'Logout' text in Toolbar after Login success .

But I guess I can not access store.

See the code again .

mounted () { EventBus.$on('LOGIN', function (payLoad) { console.log('payLoad'); console.log(this.$store); --> can not access this.isLoggedIn = this.$store.getters.isLoggedIn; --> not working this.isLoggedIn = this.checkIfIsLogged() --> not working .. }); },

How can I fix this trouble ?

Is there someone who can help me ?

Please sign in or create an account to participate in this conversation.