<html>
<head>
<meta charset="utf-8">
<title>天氣通</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<style>
div > span {
float: left
}
p {
text-align: center;
}
#test {
width: 70%;
margin: 0 auto
}
h3 {
text-align: center;
margin-left: 0;
margin-right: 2em;
}
.cities {
width: 20%;
margin: 0 auto
}
.weather_parent {
display: block;
margin-top: 50px
}
.weather_item {
width: 19%;
display: inline-block
}
</style>
</head>
<body>
<div id="test">
<h3>天氣通</h3>
<div style="width: 20%;margin:0 auto">
<input placeholder="請輸入城市名稱" v-model="city" @keyup.enter="getData()"/>
{{/*TODO 添加根據輸入推薦城市*/}}
<span style="float:right" @click="getData()">搜索</span>
</div>
<div class="cities">
<span style="margin:10px" v-for="item in cities" @click="getData(item)">{{item}}</span>
</div>
<div class="weather_parent">
<div class="weather_item" v-for="item in datas">
<p>
{{item.type}}
</p>
<p>
{{item.low}} {{item.high}}
</p>
<p>
{{item.date}}
</p>
</div>
</div>
</div>
<script>
var xmlhttp;
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執行代碼
xmlhttp = new XMLHttpRequest();
}
else {
// IE6, IE5 瀏覽器執行代碼
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// TODO 添加post與get封裝/\
var app = new Vue({
el: "#test",
data: {
response: "",
city: "",
cities: ["北京", "杭州", "上海"],
datas: []
},
methods: {
getData: function (city) {
if (city == undefined) {
city = this.city
}
var that = this
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//document.getElementById("test").innerHTML=xmlhttp.responseText;
app.response = xmlhttp.responseText;
console.log(xmlhttp.responseText)
that.datas = JSON.parse(xmlhttp.responseText).data.forecast;
}
}
xmlhttp.open("GET", "http://wthrcdn.etouch.cn/weather_mini?city=" + city, true);
xmlhttp.send();
}
}
})
</script>
</body>
</html>
vue實現一個簡單的天氣查詢
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.