0
votes

I have a problem with my Vuejs code!

I have a Vuejs application in which I installed Vue-router and Vuex! I have configured my router and I have actions in my store that allow me to extract data from my PHP API.

The problem is that I need to do things (check if an Xhr token exists in the localStorage do an xhr query with the store dispatch method to load the user-related data otherwise do nothing ) only if the user reloads the page otherwise if the user goes from page to page with the Vue-router system no request should be sent.

For that, I thought to use VueRouter BeforeRouteEnter in my App.Vue component. But the problem is that it does not work in the App.Vue (I did not understand why) but works in other components related to the routes.

I tried then to use the vuejs created() hook! It allows to make requests xhr but since these requests are asynchronous the page loads while the data have not arrived yet which leads to errors.

My App.Vue

<template>
  <div id="app" class="uk-offcanvas-content">
    <div v-if="!loading">
      <activation-alert v-if="authCheck && !activated && !arr.includes($route.name)"/>
      <navbar v-if="!isMobile"/>
      <mobile-navbar v-if="isMobile"/>
      <vue-progress-bar> </vue-progress-bar>
      <router-view />
      <off-canvas v-if="!isMobile"/>
    </div>
    <div v-else>
      <overlay-loader/>
    </div>
  </div>
</template>

<script>
import store from './store/index'
import Navbar from '@/components/Utils/Navbar/Navbar'
import MobileNavbar from './components/Mobile/Navbar'
import OffCanvas from '@/components/Utils/Navbar/OffCanvas'
import ActivationAlert from '@/components/Auth/Activation-Alert'
import OverlayLoader from '@/components/Utils/OverlayLoader'
import {mapGetters} from 'vuex'
import DeviceInformation from './Classes/DeviceInformation'

let app = {
  name: 'App',
  store,
  data () {
    return {
      arr: ['login', 'register', 'forgot-password',
        'change-password', 'blocked', 'activation'],
      loading: false
    }
  },
  components: {
    Navbar,
    OffCanvas,
    ActivationAlert,
    OverlayLoader,
    MobileNavbar
  },
  computed: {
    ...mapGetters(['activated', 'authCheck', 'isMobile'])
  },
  beforeRouteEnter (to, from, next) {
    console.log(to, from, next) // no output
  },
  mounted () {
    (new DeviceInformation(this)).load()
    this.$Progress.finish()
    global.vm = this
  },
  created () {
    let token = window.localStorage.getItem('xhrToken')
    if (typeof token !== 'undefined' && token !== null) {
      store.dispatch('setUserIfAuthenticated')
        .then(() => { this.loading = false })
    } else {
      store.dispatch('notAuth')
        .then(() => { this.loading = false })
    }

    this.$Progress.start()
    this.$router.beforeEach((to, from, next) => {
      if (to.meta.progress !== undefined) {
        let meta = to.meta.progress
        this.$Progress.parseMeta(meta)
      }
      this.$Progress.start()
      next()
    })
    this.$router.afterEach((to, from) => {
      this.$Progress.finish()
    })
  }
}
export default app
</script>

<style scoped>
  @import "../node_modules/semantic-ui-dimmer/dimmer.css";
</style>

** My Router **

import Vue from 'vue'
import Router from 'vue-router'
import Register from '../components/Auth/Register'
import Login from '../components/Auth/Login'
import Home from '../components/Home/Home'
import Test from '../components/Test'
import Blocked from '../components/Auth/Blocked'
import Profile from '../components/Auth/Profile/Profile'
import Activation from '../components/Auth/Activation'
import ForgotPassword from '../components/Auth/ChangePassword/ForgotPassword'
import ChangePassword from '../components/Auth/ChangePassword/ChangePassword'
import JustRegisteredSteps from '../components/Auth/JustRegisteredSteps'
import {auth, guest} from '../services/middleware'

Vue.use(Router)

let router = new Router({
  mode: 'history',
  saveScrollPosition: true,
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    {
      path: '/test',
      name: 'Test',
      component: Test
    },
    {
      path: '/register',
      name: 'register',
      component: Register,
      beforeEnter: guest
    },
    {
      path: '/login',
      name: 'login',
      component: Login,
      beforeEnter: guest
    },
    {
      path: '/blocked',
      name: 'blocked',
      component: Blocked,
      beforeEnter: guest
    },
    {
      path: '/forgot-password',
      name: 'forgot-password',
      component: ForgotPassword,
      beforeEnter: guest
    },
    {
      path: '/password/reset/:token',
      name: 'change-password',
      component: ChangePassword,
      beforeEnter: guest
    },
    {
      path: '/profile/:page?',
      name: 'profile',
      component: Profile,
      beforeEnter: auth
    },
    {
      path: '/activation/:action',
      name: 'activation',
      component: Activation,
      beforeEnter: auth
    },
    {
      path: '/set-profile',
      name: 'just-registered-steps',
      component: JustRegisteredSteps,
      beforeEnter: auth
    }
  ]
})

router.options.routes.forEach(function (el) {
  el['meta'] = {
    progress: {
      func: [
        {call: 'color', modifier: 'temp', argument: '#ffb000'},
        {call: 'fail', modifier: 'temp', argument: '#6e0000'},
        {call: 'location', modifier: 'temp', argument: 'top'},
        {call: 'transition', modifier: 'temp', argument: {speed: '1.5s', opacity: '0.6s', termination: 400}}
      ]
    }
  }
})
export default router
1
your app vue is where thing is getting loaded, routerhook shouldn't be triggered there??? what you are trying to do is like this-> your app vue load up everything, with some data from server(like user data) if user is logged in or you want to do other ???shahin mahmud
yes the routerHooks is not triggered but I need to load this data before the page is rendered or find another alternative! Thank you for answeringAboubacar Ouattara
@shahinmahmud No, I only want to load the logged user dataAboubacar Ouattara

1 Answers

1
votes

why dont you make the async created() so that nothings get loaded untill the data is fetched completely?