Vue JS AJAX计算属性

时间:2017-02-12 21:11:23

标签: asynchronous webpack vue.js axios

好的,我相信我非常接近我的第一个工作的Vue JS应用程序,但是在我遇到困难之后我仍然保持着小小的障碍。我希望这是最后一个小问题。 我正在使用vue-async-computed和axios从我的API中获取客户对象。

然后我将该属性传递给子组件并渲染到屏幕,如:{{customer.fName}}。

据我所知,正在进行ajax调用并且预期会返回响应,问题是页面上没有任何内容,客户对象似乎在ajax调用之后似乎没有更新。

以下是我正在处理的个人资料页面.vue文件

http://pastebin.com/DJH9pAtU

该组件有一个名为“customer”的计算属性,正如我所说,我可以在网络选项卡中看到,该请求正在进行并且没有错误。响应将发送到子组件:

 <app-customerInfo :customer="customer"></app-customerInfo>

在该组件中我将数据呈现给页面:

 {{customer.fName}}

但是,页面显示没有结果。有没有办法在检查员中验证财产“客户”的价值?我有什么明显的遗失吗?

2 个答案:

答案 0 :(得分:5)

我一直在使用Vue大约一年半,我意识到处理异步数据加载和那些好东西的斗争。以下是我设置组件的方法:

<script>
export default {

    components: {
      // your components were fine
    },

    data: function() {
      return {
         customer: {},
      }
    },

    mounted: function() {
       this.axios.get('/api/customer/get/' + this.$route.params.id)
          .then(function(response){
             this.customer = response.data;
          }.bind(this));
    }
}
</script>

所以我所做的是在组件的数据函数中初始化customer,然后当组件获得mounted时,向服务器发送axios调用。当该调用返回时,将this.customer设置为数据。就像我在上面的评论中所说的那样,一定要查看Vue's devtools,它们会让追踪变量和事件变得非常简单!

答案 1 :(得分:3)

我相信你的错误在于命名。 vue-async-computed插件需要Vue对象的新属性。

computed: {
    customer: async function() {
        this.axios.get('/api/customer/get/' + this.$route.params.id).then(function(response){
        return(response.data);
        });
    }
}

应该是:

asyncComputed: {
    async customer() {
        const res = await this.axios.get(`/api/customer/get/${this.$route.params.id}`);
        return res.data;
    }
}