- 导入Vue文件和axios文件
-
<script src="js/vue.min.js"></script>
-
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
代码部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="js/vue.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<!-- 被vm 实例所控制的区域 -->
<div id="app">
<button @click="getJoke">获取笑话</button>
<input type="text" placeholder="请输入要查询的城市名~" v-model="city">
<button @click="getWeather">天气查询</button><br/>
<a href="javascript:void(0)" @click="changeDataToGetWeather('北京')">北京</a> <a href="javascript:void(0)" @click="changeDataToGetWeather('上海')">上海</a> <a href="javascript:void(0)" @click="changeDataToGetWeather('深圳')">深圳</a>
<p>{
{
msg}}</p>
<!--用来显示笑话-->
<!-- //显示天气信息 -->
<table>
<tr v-for="item in weatherArr">
<td v-text="item.date"></td>
<td>{
{
item.high}}</td>
<td>{
{
item.fengli | formatStr}}</td>
<td>{
{
item.low}}</td>
<td>{
{
item.fengxiang}}</td>
<td>{
{
item.type}}</td>
</tr>
</table>
</div>
<script>
Vue.filter('formatStr', function(msg) {
//<![CDATA[3-4级]]>
return msg.replace('<![CDATA[', '').replace(']]>', '');
})
// 创建实例对象
const vm = new Vue({
// 指定控制的区域
el: '#app',
data: {
weatherArr: [],
msg: "-----",
city: "",
},
methods: {
getJoke() {
//发送请求
var that = this;//用变量保存Vue实例
axios.get("https://autumnfish.cn/api/joke")
.then(res => {
// console.log(res.data)
//此处的this关键字的指向不是Vue实例,所以获取不到data里面的数据
that.$data.msg = res.data;
})
.catch(err => {
console.error(err);
});
},
//获取天气信息
getWeather() {
var that = this;//用变量保存Vue实例
if (this.city == "") {
alert("城市信息不能为空!");
} else {
//调用接口。查询天气
axios.get("http://wthrcdn.etouch.cn/weather_mini?city=" + that.$data.city)
.then(res => {
that.$data.weatherArr = res.data.data.forecast;
})
.catch(err => {
console.error(err);
})
}
},
changeDataToGetWeather(cityName){
//1.把点击的城市赋值到文本框显示
this.city=cityName;
//调用获取天气方法
this.getWeather();
}
},
});
</script>
</body>
</html>
浏览器:
总结:
Vue.filter('formatStr', function(msg) {
//<![CDATA[3-4级]]>
return msg.replace('<![CDATA[', '').replace(']]>', '');
})
1.对于<![CDATA[3-4级]]>类型中内容的提取使用了字符串的替换。
//获取天气信息
getWeather() {
var that = this;//用变量保存Vue实例
if (this.city == "") {
alert("城市信息不能为空!");
} else {
//调用接口。查询天气
axios.get("http://wthrcdn.etouch.cn/weather_mini?city=" + that.$data.city)
.then(res => {
that.$data.weatherArr = res.data.data.forecast;
})
.catch(err => {
console.error(err);
})
}
},
关于Vue中this的指向,此方法属于谁,this就指向谁。对于this指向问题,可以使用变量在外部函数中代为保存。