VueJS api调用离开数据未定义

时间:2017-01-21 23:30:48

标签: javascript vue.js vuejs2

我正在学习VueJS 2.0,我正在连接到一个API,我希望在输入更改时更改某些数据的值。以下是使用开发工具输出的内容:

canadianDollar:undefined europeanEuro:undefined europeanPound:undefined usd:"1232"

每当我在USD输入字段中输入1232时,它都不会返回任何内容并将这些属性保留为未定义。这是代码。

new Vue({
  el: '#app',
  data: {
    usd: '',
    canadianDollar: '',
    europeanPound: '',
    europeanEuro: ''
  },

  // Watch methods
  watch: {
      usd: function() {
          this.convertCurrency()
      }
  },

  // Logic Methods
  methods: {
    convertCurrency: _.debounce(function() {
        var app = this;
        if (app.usd.length !== 0) {

            // Show that the things are loading in.
            app.canadianDollar = 'Searching...'
            app.europeanPound = 'Searching...'
            app.europeanEuro = 'Searching...'
            console.log(app.usd)
            axios.get("http://api.fixer.io/latest?base=USD&" + app.usd)
                .then(function(response) {
                    app.canadianDollar = response.data.CAD
                    app.europeanPound = response.data.GBP
                    app.europeanEuro = response.data.EUR
                })
                .catch(function(error){
                    app.canadianDollar = "ERROR"
                    app.europeanPound = "ERROR"
                    app.europeanEuro = "ERROR"
                })
        }
    }, 500)
  }
})

和HTML:

<!DOCTYPE html>
<html>
<head>
  <title>Welcome to Vue</title>
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
  <div id="app">
    <input type="text" name="" value="" v-model="usd">
    <ul>
        <li>Canadian Dollar: {{canadianDollar}}</li>
        <li>European Pound: {{europeanPound}}</li>
        <li>European Euro: {{europeanEuro}}</li>
    </ul>
  </div>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js" charset="utf-8"></script>
  <script src="index.js" charset="utf-8"></script>
</body>
</html>

当我输入一个数字时,它确实给了我&#34;搜索&#34;部分但消失,没有任何显示。

2 个答案:

答案 0 :(得分:1)

我建议改变

then(function(response) {
   app.canadianDollar = response.data.CAD
   app.europeanPound = response.data.GBP
   app.europeanEuro = response.data.EUR
})

then(function(response) {
   console.log(response);
})

你可以看到返回的内容。

另外,axios.get("http://api.fixer.io/latest?base=USD&" + app.usd)可能应该有一个像vulue:axios.get("http://api.fixer.io/latest?base=USD&VALUE=" + app.usd)这样的名字,但是你必须检查他们的api,看看它的名字是什么。

答案 1 :(得分:0)

...

response.data.rates.CAD;

你有

response.data.CAD;

...

app.canadianDollar = response.data.rates.CAD * app.usd;