一. 在组件中使用axios获取数据
1. 安装和配置axios
默认情况下,我们的项目中并没有对axios包的支持,所以我们需要下载安装。
在项目根目录中使用 npm安装包
npm install axios
接着在main.js文件中,导入axios并把axios对象 挂载到vue属性中作为一个子对象,这样我们才能在组件中使用。
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import axios from 'axios' // 从node_modules目录中导包(这样写就行) Vue.config.productionTip = false; Vue.prototype.$axios = axios; // 把对象挂载到Vue中 /* eslint-disable no-new */ new Vue({ el: '#app', components: { App }, template: '<App/>' });
2.在组件中使用axios获取数据
新建子组件GetWeather.vue文件
前提是将GetWeather注册到App.vue下
<template> <div id="GetWeather"> <input type="text" v-model="city" placeholder="请输入要查询的城市"> <button @click="get_weather">获取天气</button> <p>{{weather_info}}</p> <hr> <div v-for="k,v in weather_info.data"> <p>{{v}}:{{k}}</p> </div> </div> </template> <script> export default { name: "GetWeather", data() { return { city: "", weather_info: "", } }, methods: { get_weather() { this.$axios.get("http://wthrcdn.etouch.cn/weather_mini", { params: { "city": this.city } }).then(response => { this.weather_info = response.data; }).catch(error => { console.log(error.response) }) } } } </script> <style scoped> </style>