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

标签 javascript vue.js synchronous vue-resource

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

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

这个错误是因为vue渲染了auth data而api的请求还没有完成。

是否可以让 vue 在 vue 渲染auth data 之前先等待请求 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>

最佳答案

您所说的问题是您尝试访问一个不存在的对象,并且由于错误,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 中被弃用

关于javascript - Vuejs 在渲染数据之前同步请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37733935/

相关文章:

javascript - 在外部 .js 文件中使用 .vue 组件时如何使用相同的变量?

javascript - 微前端/Web 组件/Vue 路由器错误 : Uncaught TypeError: Cannot redefine property: $router

Meteor wrapAsync 语法

RestKit 使用 sendSynchronously 方法的最佳实践

javascript - NodeJs,javascript : . forEach 似乎是异步的?需要同步

javascript - 用户 getSessionToken() 返回未定义

javascript - 使滚动效果也适用于点击

javascript - Jquery animate backgroundColor 不工作

javascript - 在Node JS中,Require Express和HTTP一起和分开有什么区别

javascript - 如何在Vue JS组件中使用全局变量?