Vue结合axios的综合案例
程序员文章站
2022-03-01 12:39:26
...
前台页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue中结合Axios完成天气查询案例</title>
<script src="../js/vue.min.js"></script>
</head>
<body>
<div id="app">
<input type="text"/> <button type="button">搜索</button> <br/>
<span>
<a href="">北京</a>
<a href="">上海</a>
<a href="">广州</a>
<a href="">重庆</a>
</span>
<hr>
<span>北京,今天的天气是:晴转多云,空气良好!</span>
</div>
</body>
</html>
后台接口:构建一个控制器
//查询城市的接口
@RestController
@RequestMapping("/city")
public class CityController {
@GetMapping("find")
@CrossOrigin
public Map<String,String> findWeatherByCity(String name){
Map<String, String> map = new HashMap();
String weathers = getWeathers(name);
map.put(name,weathers);
return map;
}
//返回对应城市天气
public String getWeathers(String name){
Map<String, String> weathers = new HashMap<>();
weathers.put("北京","晴转多云,空气清晰");
weathers.put("上海","多云转晴,空气清晰");
weathers.put("广州","大雨转小雨,空气清晰");
weathers.put("重庆","大太阳,空气清晰");
weathers.put("天津","离北京比较近,和北京差不多");
return weathers.get(name);
}
}
遍历城市天气:(改)
<div id="app">
<!-- v-model绑定城市名 -->
<input type="text" v-model="name"/> <button type="button">搜索</button> <br/>
<span v-for="city in hostCitys">
<a href="" > {{city}} </a>
</span>
<hr>
<span>北京,今天的天气是:晴转多云,空气良好!</span>
</div>
实现功能:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue中结合Axios完成天气查询案例</title>
<script src="../js/vue.min.js"></script>
</head>
<body>
<div id="app">
<!-- @keyup.delete="shows"监听删除键是否展示 -->
<!-- @keyup.enter="searchCity"监听搜索 -->
<input type="text" v-model="name" @keyup.delete="shows" @keyup.enter="searchCity"/>
<button type="button" @click="searchCity">搜索</button> <br/>
<span v-for="city in hostCitys">
<a href="" @click.prevent="searchCitys(city)" > {{city}} </a>
</span>
<hr>
<span v-show="isShow"> {{name}},今天的天气是:{{message}}</span>
</div>
<!-- 引入axios -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
name:'',
hostCitys:['北京','上海','广州','重庆'],
message:'',
isShow: false,
},
methods: {
searchCity() {
//获取输入的城市信息
console.log(this)
// 把this保存下来
let _this = this
//发送axios请求
axios.get("http://localhost:7001/city/find?name=" + this.name).then(function(response) {
console.log(response.data.message)
_this.message = response.data.message
// 把保存下来的_this取出来
_this.isShow = true
}).catch(function(err){
console.log(err)
})
},
searchCitys(name) {
this.name = name
this.searchCity(); //函数中调用函数
},
// 监听删除键方法是否展示
shows() {
this.isShow = false
}
},
})
</script>
</body>
</html>
上一篇: [Leetcode] Reverse Nodes in k-Group
下一篇: Redis 理解