我有需要身份验证的单页应用程序。当用户通过身份验证然后访问某些页面或点击浏览器中的重新加载按钮时,它将请求提供其身份验证数据的 api。然后我有这样的错误:
[Vue warn]: Error when evaluating expression "auth.name": TypeError: Cannot read property 'name' of null (found in component: <navbar>)
这个错误是因为vue渲染了 auth数据,而api的请求还没有完成。
是否可以让 vue 在 vue 渲染 授权数据 之前先等待请求 api 直到完成?
更清楚这里发生了什么。这是代码:
// main.js
import Vue from 'vue'
import App from './App.vue' // root vue
import store from './vuex/store' // vuex
import router from './router' // my 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 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
})
},
data () {
return {
authData: null // default is null until the api finish the process
}
}
</script>
// end App.vue
// SomeRouterComponents.vue
<template>
<!-- some content -->
<div>
// always got error: cannot read property 'name' of null
// here I expect to render this after api has been resolved
{{ $root.authData.name }}
</div>
<!-- some content -->
</template>
原文由 antoniputra 发布,翻译遵循 CC BY-SA 4.0 许可协议
你所说的问题是你试图访问一个不存在的对象,并且由于错误,Vue 无法在下一个滴答中呈现它。解决方案是使用一个简单的
v-if
检查数据是否已加载,这仅适用于反应性数据。根组件
其他组件
我使用了
v-if="!dataReady"
而不是v-else
因为它将在 Vue 2.0 中被弃用