Vuejs从.js文件返回数据

时间:2017-09-15 18:55:16

标签: javascript vuejs2

我是Vue的新手,正在使用应用程序从天气api获取天气。
如果我将axios.get()留在Content.vue中,则下面的代码可以使用 我想将它移动到一个单独的文件(WeatherAPI.js)并从那里调用它。如果我在axois.get()中发表评论Content.vue并取消注释this.todaysWeather = WeatherAPI.returnTodaysWeather();,那么它就无法运作。我确实看到数据从WeatherAPI.js记录到控制台,所以它正在获取它,但它似乎没有正确地返回它。我在undefined的控制台日志中看到了Content.vue

Content.vue

<template>
<div class="container-fluid">
    <div class="row answerRow text-center">
        <div class="col">
        </div>
    </div>
    <div class="row">
        <div class="col">
            <weather-today :todaysWeather="todaysWeather"></weather-today>
        </div>
        <div class="col">
            Column2
        </div>
    </div>
</div>
</template>

<script>
import Today from '../weather/Today.vue'
import WeatherAPI from '../data/WeatherAPI.js'
import axios from 'axios'
const apiURL = "http://api.openweathermap.org/data/2.5/weather";
const apiKey = "MyKeyHere";
const zipCode = "11111,us";
const dailyWeatherUrl = apiURL + "?zip=" + zipCode + "&appid=" + apiKey;
export default {
    mounted(){
        this.getTodaysWeather();
        console.log(this.todaysWeather)
    },
    data () {
        return {
            todaysWeather: {name: "testname"}
        }
    },
    components: {
        'weather-today': Today
    },
    methods: {
        getTodaysWeather () {
            //this.todaysWeather = WeatherAPI.returnTodaysWeather();            
            axios.get(dailyWeatherUrl)
                .then((response) => {
                    console.log(response.data);
                    this.todaysWeather = response.data;
                })
                .catch(function (error) {
                    console.log(error);
                });


        }
    }
}
</script>

<style>
.answerRow{
    background-color: yellow;
}
</style>

Today.vue

<template>
    <div class="container row1">
        <div class="row">
            <div class="col">
                <h2>Todays Weather</h2>
            </div>
        </div>            
        <div class="row">
            <div class="col">
                City: {{ todaysWeather.name }}
            </div>
        </div>   
    </div>
</template>

<script>
import WeatherAPI from '../data/WeatherAPI.js'
export default {
    props: ['todaysWeather'],
    mounted() {
        console.log(this.todaysWeather)
    }    
}
</script>

<style>
.row1{
    background-color: #3498DB;
}
</style>

WeatherAPI.js

const apiURL = "http://api.openweathermap.org/data/2.5/weather";
const apiKey = "MyKeyHere";
const zipCode = "11111,us";
const dailyWeatherUrl = apiURL + "?zip=" + zipCode + "&appid=" + apiKey;

import axios from 'axios';
export default {   
  data(){
    return {
      todaysWeather: {}
    }
  },
    returnTodaysWeather () {
        axios.get(dailyWeatherUrl)
        .then((response) => {
          console.log(response.data);
          this.todaysWeather = response.data;
          console.log(this.todaysWeather);
          return this.todaysWeather;
        })
        .catch(function (error) {
          console.log(error);
        });
    }


}

1 个答案:

答案 0 :(得分:3)

您的WeatherAPI.js文件实际上与Vue无关,它应该只是一个包含与天气API交互的方法的文件。

<强> WeatherAPI.js

const apiURL = "http://api.openweathermap.org/data/2.5/weather";
const apiKey = "MyKeyHere";
const zipCode = "11111,us";
const dailyWeatherUrl = apiURL + "?zip=" + zipCode + "&appid=" + apiKey;

import axios from 'axios';

export function returnTodaysWeather () {
  return axios.get(dailyWeatherUrl)
           .then(response => response.data)
}

请注意,此函数返回一个promise。我们稍后会使用它。此外,此代码直接导出函数。如果您愿意,可以以不同方式导出具有与API交互的多个函数的对象。

现在在Content.vue,你需要做的就是导入你想要使用的天气API。

<强> Content.vue

// import the returnTodaysWeather function from the api file
import { returnTodaysWeather } from '../data/WeatherAPI.js'

export default {
    mounted(){
        this.getTodaysWeather();
        console.log(this.todaysWeather)
    },
    data () {
        return {
            todaysWeather: {name: "testname"}
        }
    },
    components: {
        'weather-today': Today
    },
    methods: {
        getTodaysWeather () {
            // The API returns a promise. In the callback from the 
            // promise, we can set the Vue's data with the results
            // of the call to the API
            returnTodaysWeather().then(weather => this.todaysWeather = weather)           
        }
    }
}

我删除了错误处理,但在生产中,您显然希望来自API的catch错误。