09.1.VUE学习之watch监听属性变化实现类百度搜索栏功能ajax异步请求数据,返回数组
09.1html里
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>vue</title>
<link rel="stylesheet" href="">
<!--<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>-->
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript" src="../vue/node_modules/axios/dist/axios.js"></script>
<script type="text/javascript" src="../vue/node_modules/lodash/lodash.js"></script>
</head>
<body>
<div id="vue">
<!--当input里的值改变时,会改变data里的word-->
<input type="text" v-model="word">
<h1>
<!--拿到data里的result里的值-->
</h1>
<table border="1">
<tr>
<th>序号</th>
<th>编号</th>
<th>标题</th>
<th>价格</th>
<th>数量</th>
<th>合计</th>
</tr>
<tbody>
<!--拿到data里的result里的值-->
<tr v-for="(v,k) in result">
<td>{{k}}</td>
<td>{{v.id}}</td>
<td>{{v.title}}</td>
<td>{{v.price}}</td> <!--每次都取name值,不变-->
<td>{{v.num}}</td> <!--每次都取name值,不变-->
<td>{{v.num*v.price}}</td> <!--每次都取name值,不变-->
</tr>
总价格:{{total}}
</tbody>
</table>
</div>
</body>
<script type="text/javascript">
var app=new Vue({
el:'#vue',
watch:{ //监听data里的word的变化
// 拿到input里的新值和旧值
word:_.debounce(
function(new_v,old_v){
// console.log(new_v+'=>'+old_v);
var url = '9.1.php?word='+new_v;
// ajax get异步请求
axios.get(url).then(function(response){
console.log(response);
console.log(response.data.total);
app.total = response.data.total //赋值给data里的result
app.result = response.data.content //赋值给data里的result
});
},1000 //1秒后执行
)
},
data:{
word:'',
result:'',
total:0,
}
});
</script>
</html>
09.1.php里
<?php
//print_r('要搜索的内容是:'.$_GET['word']);
$data = [
'total'=>0,
'content'=>array(
['id' => 1, 'title' => 'iphone7Plus', 'price' => 300, 'num' => 3,],
['id' => 2, 'title' => 'hdcms系统', 'price' => 1999, 'num' => 9],
),
];
$total=0;
foreach($data['content'] as $k=>$v){
$total+=$v['price']*$v['num']; //计算总价
}
$data['total']=$total;
echo json_encode($data);
?>
效果:
[Haima的博客]
http://www.cnblogs.com/haima/