【问题标题】:Return data from rest api从rest api返回数据
【发布时间】:2017-09-02 04:11:05
【问题描述】:

我正在尝试从 rest api 获取一些数据。然而,结果 this.someData 仍未定义。

我的组件如下

<template>
  <div class="list">
    <h1>List</h1>
    <pre>msg: {{msg}}</pre>
  </div>
</template>

<script>
  import Vue from 'vue'
  import VueResource from 'vue-resource'
  Vue.use(VueResource)

  export default {
    name: 'list',
    data () {
      this.$http.get('http://localhost:8080/api/posts/filter?username=tons').then(response => {
      // get body data
        this.someData = response.body
        console.log(this.someData)
      }, response => {
      // error callback
      })

      return {
        msg: this.someData + 'somedata'
      }
    }
  }
</script>

有人知道我做错了什么吗?

【问题讨论】:

  • 如果您在浏览器中转到http://localhost:8080/api/posts/filter?username=tons,您会看到结果吗?

标签: vue.js vue-resource


【解决方案1】:

'data' 应该只是属性。有一些“方法”可以让您获取一些东西,然后填充您的“数据”属性。

正确的代码如下所示:

<script>
    export default {
        data: function() {
            return {
                someData: null
            }
        },
        methods: {
            getData: function() {
                // fetch here
                this.someData = response.body;
            }
        },
        mounted() {
            this.getData(); // or trigger by click or smth else
        }
    }
</script>

然后您可以在您的模板中{{ someData }}

@Bert_Evans 是对的,您可以在“数据”中进行一些基本计算,但它们应该是同步的,因为 Vue 中反应性的工作方式。

【讨论】:

  • 在返回对象之前对数据进行一些计算是完全可以接受的。只是在这种情况下。
  • 可以,但不获取数据。
  • 这是 Evan You(Vue 的创建者)在 data() 中使用异步方法的示例。一切都在于你如何去做。 jsfiddle.net/yyx990803/kyt43L2r
  • @BertEvans 哇,有一些很好的高级东西!非常感谢这个链接!
猜你喜欢
  • 2017-11-26
  • 2016-06-13
  • 1970-01-01
  • 2014-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-18
相关资源
最近更新 更多