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

ant*_*tra 12 javascript synchronous vue.js vue-resource

我有单页面应用程序需要身份验证.当用户通过身份验证然后访问某些页面或点击浏览器中的重新加载按钮时,它将请求提供其身份验证数据的API.然后我有这样的错误:

[Vue warn]: Error when evaluating expression "auth.name": TypeError: Cannot read property 'name' of null (found in component: <navbar>)

导致此错误的原因是,当对api的请求尚未完成时,vue呈现auth数据.

是否可以使vue等待请求api直到完成,在vue渲染auth数据之前?

更清楚的是这里发生了什么.这是代码:

// 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>
Run Code Online (Sandbox Code Playgroud)

Yer*_*lma 13

您所说的问题是您尝试访问不存在的对象,并且由于该错误,Vue无法在下一个tick中呈现它.解决方案是使用简单的方法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
    }
  }
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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

  • 因为如果我使用您提供的解决方案。它会在每个 routerComponent 中有许多 v-if="dataReady"。 (2认同)