VUE框架 组件中发生Ajax请求【天气预报案例扩展】

<template>
<router-view/>
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
nav {
padding: 30px;
}
nav a {
font-weight: bold;
color: #2c3e50;
}
nav a.router-link-exact-active {
color: #42b983;
}
</style>

<template>
<div class="home">
<Nav></Nav>
<Forecast></Forecast>
</div>
</template>
<script>
// @ is an alias to /src
import Nav from '@/components/Nav.vue'
import Forecast from '@/components/Forecast.vue'
export default {
name: 'HomeView',
components: {
Nav,
Forecast,
}
}
</script>

<template>
<h1>天气预报</h1>
<p> <input type="text" placeholder="请输入查询城市" v-model="city">
<button @click="sendAjax">查询</button>
</p>
<div>{{forecast}}</div>
<table border="1" v-if="forecasts.length>1">
<tr>
<td>日期</td>
<td>类型</td>
<td>最高气温</td>
<td>最低气温</td>
<td>风向</td>
</tr>
<tr v-for="day_forecast in forecasts">
<td>{{day_forecast.date}}</td>
<td>{{day_forecast.type}}</td>
<td>{{day_forecast.high}}</td>
<td>{{day_forecast.low}}</td>
<td>{{day_forecast.fengxiang}}</td>
</tr>
</table>
</template>
<script>
import axios from "axios";
export default {
name: "Forecast",
data(){
return{
forecasts: [],
city:"衡水"
}
},
methods: {
sendAjax(){
var that = this;
axios.get("http://wthrcdn.etouch.cn/weather_mini",{
params: {
city: that.city,
}
}).then(function (response) {
console.log("response",response);
that.forecasts = response.data.data.forecast
})
},
},
created(){
this.sendAjax()
},
}
</script>
<style scoped>
tr td{
padding: 10px;
width: 100px;
}
table{
margin: 0 auto;
}
</style>

<template>
<div>
<ul>
<li v-for="menu in menu_list"><a :href="menu.link">{{ menu.name }}</a></li>
<li>
<span>所在地:</span><select v-model="city" name="" id="">
<option value="北京">北京</option>
<option value="上海">上海</option>
<option value="深圳">深圳</option>
</select>
</li>
</ul>
</div>
</template>
<script>
export default {
name: "Nav",
data() {
return {
menu_list: [
{name: "百度", "link": "http://www.baidu.com"},
{name: "腾讯", "link": "http://www.qq.com"},
{name: "小米", "link": "http://www.xiaomi.com"},
],
city:"北京",
}
},
}
</script>
<style scoped>
ul, li {
list-style: none;
padding: 0;
margin: 0;
}
ul::after {
overflow: hidden;
clear: both;
display: block;
content: "";
}
li {
float: left;
margin: 0 20px;
}
a {
text-decoration: none;
color: #666;
}
</style>

注意避暑防晒哦!!!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?