(1)下载,安装lodash 库
npm install lodash --save
(2)页面中引入lodash.js
<!-- 页面里引入js --> <script src="./js/lodash.js"></script>
(3)使用_.debounce函数
应用场景:
_.debounce(func, [wait=0], [options={}])
(4) 具体操作
访问 天气的接口地址
http://wthrcdn.etouch.cn/weather_mini?city='合肥'
完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<h1>watch 侦听 异步数据的变化,同时通过lodash减轻向服务器发送请求的压力</h1>
<div>
城市: <input type="text" v-model.trim="word">
</div>
<hr>
<div>
<table border="1" width="800">
<thead>
<tr>
<th>日期</th>
<th>低温</th>
<th>高温</th>
<th>风力</th>
<th>风向</th>
<th>天气</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in list" :key="index">
<td>{{item.date}}</td>
<td>{{item.low}}</td>
<td>{{item.high}}</td>
<td>{{item.fengli}}</td>
<td>{{item.fengxiang}}</td>
<td>{{item.type}}</td>
</tr>
</tbody>
</table>
</div>
</div>
<script src="./js/vue.js"></script>
<script src="./js/axios.js"></script>
<script src="./js/lodash.js"></script>
<script>
var vm = new Vue({
el:'#app',
data(){
return{
word:'',
list:[],
}
},
// 侦听器
watch:{
word:_.debounce(function(newVal,oldVal){
console.log('旧值:'+oldVal);
console.log('新值:'+newVal);
// 将 新值 作为 异步请求的参数 发送给 服务器
// 天气接口地址
var apiUrl = `http://wthrcdn.etouch.cn/weather_mini?city=${newVal}`;
axios.get(apiUrl)
.then(function(result){
console.log(this);
// console.log(result.data.data.forecast);
this.list = result.data.data.forecast;
console.log(this.list);
})
},3000) //延迟3秒才输出结果
},
methods:{
}
})
</script>
</body>
</html>
预览效果: