09.VUE学习之watch监听属性变化实现类百度搜索栏功能ajax异步请求数据,返回字符串
cmd下安装axios
npm install axios
安装好后,会多出node_modules文件夹
思路:
监听data里的word改变时,发送ajax异步请求数据,
把返回的数据赋值给data里的result,再传给模板里
9.html
<!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="node_modules/axios/dist/axios.js"></script>
</head>
<body>
<div id="vue">
<!--当input里的值改变时,会改变data里的word-->
<input type="text" v-model="word">
<h1>
<!--拿到data里的result里的值-->
结果:{{result}}
</h1>
</div>
</body>
<script type="text/javascript">
var app=new Vue({
el:'#vue',
watch:{ //监听data里的word的变化
// 拿到input里的新值和旧值
word:function(new_v,old_v){
// console.log(new_v+'=>'+old_v);
var url = '9.php?word='+new_v;
// ajax get异步请求
axios.get(url).then(function(response){
console.log(response);
app.result = response.data //赋值给data里的result
});
}
},
data:{
word:'',
result:''
}
});
</script>
</html>
9.php里
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/1/5
* Time: 10:42
*/
print_r('要搜索的内容是:'.$_GET['word']);
?>
效果:
[Haima的博客]
http://www.cnblogs.com/haima/