简体   繁体   English

尝试使用VueJs和Axios显示对象

[英]Trying to display object with VueJs and Axios

I'm expanding my knowledge learning VueJs, and for learning reasons, I am trying to use axios library to get JSON information. 我正在扩展我的学习VueJs的知识,并且出于学习的原因,我正在尝试使用axios库来获取JSON信息。 The problem is displaying an object in HTML. 问题是在HTML中显示一个对象。 Printing everything in the console works fine, except doing it HTML. 除了HTML之外,在控制台中打印所有内容都可以正常工作。

When I load a page, it displays nothing, while in the console it shows all results. 当我加载页面时,它什么都不显示,而在控制台中它显示所有结果。

HTML file: 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 file: 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');
    }
});

Thank you in advance. 先感谢您。

There are a few problems with your code... 您的代码存在一些问题......

  • Your response handlers are not setting the data fields of your Vue instance. 您的响应处理程序未设置Vue实例的数据字段。 For instance, in the following code. 例如,在以下代码中。 dataReceived does not refer to dataReceived of your Vue object, which would require this.dataReceived . dataReceived不引用您的Vue对象的dataReceived ,这需要this.dataReceived

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

    You can use an ES2015 arrow-function to bind this to your Vue instance, then call this.dataReceived = response . 您可以使用ES2015箭头功能绑定this到您的Vue公司的实例,然后调用this.dataReceived = response

     axios.get('...') .then((response) => { this.dataReceived = response; console.log(dataReceived); }) 
  • Your template attempts to bind the getDescription function to the text content of a <div> with {{getDescription}} , but the correct syntax is {{getDescription()}} (note the parentheses). 您的模板尝试将getDescription函数绑定到带有{{getDescription}}<div>的文本内容,但正确的语法是{{getDescription()}} (请注意括号)。

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

    However, since the data used in getDescription is not available until the AJAX response returns, the binding should actually be something that gets updated by the newly received data. 但是,由于getDescription使用的数据在AJAX响应返回之前不可用,因此绑定实际上应该是新接收的数据更新的内容。 For instance, this binding could be a data field (eg, named title ) that is set by the AJAX response handler. 例如,该绑定可以是由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 演示

To access properties in the data option, you need to use the this keyword, similar to how you accessed the getJson method. 要访问data选项中的属性,需要使用this关键字,类似于访问getJson方法的方式。

For instance, to access the dataReceived variable in the .then of your AJAX call, you will need to adjust the following: 例如,访问dataReceived可变的.then你的AJAX调用,你将需要调整如下:

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

Use this to access any other of a components options (data values, computed values, methods, etc.) 使用this来访问任何其他组件选项(数据值,计算值,方法等)

Change your binding to {{dataReceived}} and update your Vue instance like this 将绑定更改为{{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");
  }
});

As the other responses noted, your variables in Vue are always children of a Vue instance, and should be set as such, using this.varName. 正如其他响应所指出的那样,Vue中的变量始终是Vue实例的子项,应使用this.varName进行设置。 Additionally, binding to the response of an async call will just give you the immediate return, which would (I believe) be a promise. 此外,绑定到异步调用的响应只会给你立即返回,这将(我相信)是一个承诺。 Welcome to Vue, it's awesome! 欢迎来到Vue,真棒!

edit: my use of mounted instead of beforeMount was just a personal choice as I was writing this, it should still work. 编辑:我使用的mounted而不是beforeMount只是个人选择,因为我写这个,它应该仍然有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM