Vuejs 在渲染数据之前同步请求

新手上路,请多包涵

我有需要身份验证的单页应用程序。当用户通过身份验证然后访问某些页面或点击浏览器中的重新加载按钮时,它将请求提供其身份验证数据的 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 许可协议

阅读 418
1 个回答

你所说的问题是你试图访问一个不存在的对象,并且由于错误,Vue 无法在下一个滴答中呈现它。解决方案是使用一个简单的 v-if 检查数据是否已加载,这仅适用于反应性数据。

根组件

  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
    }
  }

其他组件

  <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>

我使用了 v-if="!dataReady" 而不是 v-else 因为它将在 Vue 2.0 中被弃用

原文由 Yerko Palma 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题