尝试使用 VueJs 和 Axios 显示对象

Trying to display object with VueJs and Axios

我正在学习VueJs扩展我的知识,并且出于学习原因,我正在尝试使用axios库来获取JSON信息。 问题是在 HTML 中显示一个对象。在控制台中打印所有内容工作正常,除了 HTML.

当我加载页面时,它什么都不显示,而在控制台中却显示所有结果。

HTML 文件:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <script src="https://unpkg.com/vue"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <title>VueJs</title>
  </head>
  <body>
    <div class="innerBody" id="app">
        <p style="width: 100%; height: 40px; background: gray;">{{getDescription}}</p>
    </div>
    <script src="app.js"></script>
  </body>
</html>

JS文件:

new Vue({
    el: '#app',
    data:{
        dataReceived: [],
        errorReceived: [],
        description: '',
    },
    methods: {
        getJson: function(city){
            axios.get('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22'+city+'%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys')
            .then(function (response) {
                dataReceived = response;
                console.log(dataReceived);
                return dataReceived;
            })
            .catch(function (error) {
                errorReceived = error;
                console.log(errorReceived);
                return errorReceived;
            });
         },
        getDescription: function(){
            description = dataReceived.data.query.results.channel.title;
            console.log(description);
            return description;
        }
    },
    beforeMount(){
        this.getJson('boston');
    }
});

提前致谢。

要访问数据选项中的属性,您需要使用 this 关键字,类似于您访问 getJson 方法的方式。

例如,要访问 AJAX 调用的 .then 中的 dataReceived 变量,您需要调整以下内容:

axios.get('your-url')
.then(function (response) {
    this.dataReceived = response;
    console.log(this.dataReceived);
    return this.dataReceived;
})

使用this访问任何其他组件选项(数据值、计算值、方法等)

您的代码存在一些问题...

  • 您的响应处理程序没有设置您的 Vue 实例的数据字段。例如,在下面的代码中。 dataReceived 不引用 Vue 对象的 dataReceived,这需要 this.dataReceived.

    axios.get('...')
            .then(function (response) {
                dataReceived = response; // <-- should be: this.dataReceived
                console.log(dataReceived);
                return dataReceived;
            })
    

    您可以使用 ES2015 arrow-functionthis 绑定到您的 Vue 实例,然后调用 this.dataReceived = response.

    axios.get('...')
            .then((response) => {
                this.dataReceived = response;
                console.log(dataReceived);
            })
    
  • 您的模板尝试将 getDescription 函数绑定到带有 {{getDescription}}<div> 的文本内容,但正确的语法是 {{getDescription()}} (注意括号)。

    <div id="app">{{getDescription()}}</div>
    

    但是,由于在 getDescription 中使用的数据在 AJAX 响应 returns 之前不可用,因此绑定实际上应该由新接收的数据更新。例如,此绑定可以是由 AJAX 响应处理程序设置的数据字段(例如,命名为 title)。

    new Vue({
      ...
    
      data() {
        return {
          dataReceived: {},
          title: ''
        }
      },
    
      methods: {
        getsJon() {
          axios.get('...')
            .then((response) => {
              this.dataReceived = response;
              this.title = parseTitle(this.dataReceived);
            });
        },
    
        parseTitle(data) {
          return /* ... */;
        }
      }
    });
    
    // HTML
    <div id="app">{{title}}</div>
    

demo

将您的绑定更改为 {{dataReceived}} 并像这样更新您的 Vue 实例

new Vue({
  el: "#app",
  data: {
    dataReceived: [],
    errorReceived: [],
    description: ""
  },
  methods: {
    getJson: function(city) {
      axios
        .get(
          "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22" +
            city +
            "%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"
        )
        .then(response => {
          this.dataReceived = response;
          console.log(this.dataReceived);
        })
        .catch(error => {
          this.errorReceived = error;
          console.log(this.errorReceived);
        });
    },
    getDescription: function() {
      this.description = this.dataReceived.data.query.results.channel.title;
      console.log(this.description);
    }
  },
  mounted: function() {
    this.getJson("boston");
  }
});

正如其他回复所指出的,您在 Vue 中的变量始终是 Vue 实例的子项,并且应该使用 this.varName 进行设置。此外,绑定到异步调用的响应只会给你立即 return,这(我相信)是一个承诺。欢迎使用 Vue,它很棒!

编辑:我使用 mounted 而不是 beforeMount 只是我写这篇文章时的个人选择,它应该仍然有效。