vue-async-data无效

时间:2017-04-27 18:12:42

标签: javascript vue.js vuejs2 vue-component

我正在尝试使用vue-async-data在呈现我的Vue组件之前异步获取数据,但我没有成功。我没有得到任何错误,但它根本不起作用。

这是我的 main.js 代码:

import Vue from 'vue'
import VueAsyncData from 'vue-async-data'
import router from './router'
import App from './App.vue'

Vue.use(VueAsyncData)

new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App }
})

这是我的 App.vue 代码:

<template>
  <div>
    {{ msg }}
    <navigation wait-for="async-data"></navigation>
  </div>
</template>

<script>

import Navigation from './components/Navigation.vue'

export default {
  name: 'app',
  components: {
    Navigation
  },
  data: function() {
    return {
      msg: 'not loaded yet...'
    }
  },
  asyncData: function (resolve, reject) {
    // load data and call resolve(data)
    // or call reject(reason) if something goes wrong
    setTimeout(function () {
      // this will call `vm.$set('msg', 'hi')` for you
      resolve({
        msg: 'hi'
      })
    }, 1000)
  }
}
</script>

msg 值在任何时候都不会更改,但仍会呈现该组件。

我错过了somenthing吗?

1 个答案:

答案 0 :(得分:2)

正如Bert Evans所说,vue-async-data不适用于Vue 2.0。

我使用了vue-router和创建的函数来实现我所需要的(如https://router.vuejs.org/en/advanced/data-fetching.html中所述。

<template>
  <div>
    <div class="loading" v-if="loading">
      Loading...
    </div>

    <div v-if="error" class="error">
      {{ error }}
    </div>

    <navigation v-if="currentUser"></navigation>
  </div>
</template>

<script>

import Navigation from './components/Navigation.vue'

export default {
  name: 'app',
  components: {
    Navigation
  },
  data: function() {
    return {
      loading: true,
      error: false,
      currentUser: null
    }
  },
  created: function() {
    this.fetchUserData()
  },
  methods: {
    fetchUserData: function() {
      this.$http.get('/Account/CurrentUserInfo').then(data => {
        this.currentUser = data
        this.loading = false
      }, response => {
        this.loading = false
        this.error = true
      });
    }
  }
}

</script>