Vuejs synchronously request before render data Vuejs synchronously request before render data vue.js vue.js

Vuejs synchronously request before render data


The problem as you said is that you try to access an object that isn't present, and because of the error, Vue can't render it in the next tick. The solution is to use a simple v-if to check if the data is loaded, this work only for reactive data.

root component

  import auth from './services/auth' // import authservice  ready () {    // here is code that should be done first before vue render all authData    auth.getUser((response) => {      self.authData = response      self.dataReady = true    })  },  data () {    return {      authData: null, // default is null until the api finish the process      dataReady: false    }  }

otherComponent

  <div v-if="dataReady">    // note that if you use v-show you will get the same error    {{ $root.authData.name }}  </div>  <div v-if="!dataReady">    // or some other loading effect    Loading...  </div>

I used v-if="!dataReady" instead of v-else because it will be deprecated in Vue 2.0


You could use the data transition hook with the waitForDataoption enabled:

<script>  import authService from './services/auth'  export default {    route: {      waitForData: true, // wait until data is loaded      data (transition) {        authService.getUser((response) => {          transition.next({ authData: response }) // set data        })      }    },    data () {      return {        authData: null      }    }  }</script>

Also, if you don't want to use that option, you could check if the data is loaded by using the $loadingRouteData property.

More details here:http://router.vuejs.org/en/pipeline/data.html


You could just prevent Vue from trying to access the object property, like this:

{{ $root.authData ? $root.authData.name : null }}

You could even change null for a Loading... message in some cases.