javascript - Vuejs synchronously request before render data -
i have single page application requires authentication. when user authenticated visit pages or hit reload button in browser request api provide auth data. have error this:
[vue warn]: error when evaluating expression "auth.name": typeerror: cannot read property 'name' of null (found in component: <navbar>)
this error caused because vue render auth data while request api have not finished yet.
is possible make vue wait request api until finish first, before vue render auth data?
just more going on here. here code:
// main.js import vue 'vue' import app './app.vue' // root vue import store './vuex/store' // vuex import router './router' // router map sync(store, router) router.start(app, '#app') // end main.js // app.vue <template> <main> <div class="wrapper"> <router-view></router-view> </div> </main> </template> <script> import authservice './services/auth' // import authservice ready () { // here code should done first before vue render authdata auth.getuser((response) => { self.authdata = response }) }, data () { return { authdata: null // default null until api finish process } } </script> // end app.vue // someroutercomponents.vue <template> <!-- content --> <div> // got error: cannot read property 'name' of null // here expect render after api has been resolved {{ $root.authdata.name }} </div> <!-- content --> </template>
the problem said try access object isn't present, , because of error, vue can't render in next tick. solution use simple v-if
check if data loaded, work reactive data.
root component
import auth './services/auth' // import authservice ready () { // here code should done first before vue render authdata auth.getuser((response) => { self.authdata = response self.dataready = true }) }, data () { return { authdata: null, // default null until api finish process dataready: false } }
othercomponent
<div v-if="dataready"> // note if use v-show same error {{ $root.authdata.name }} </div> <div v-if="!dataready"> // or other loading effect loading... </div>
i used v-if="!dataready"
instead of v-else
because deprecated in vue 2.0
Comments
Post a Comment