虽然计算属性在大多数情况下更合适,但有时也需要一个自定义的侦听器。这就是为什么 Vue 通过 watch 选项提供了一个更通用的方法,来响应数据的变化。当需要在数据变化时执行异步或开销较大的操作时,这个方式是最有用的。
代码:
前端代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="app1">
请输入您的问题:<input type="text" v-model="question"/><br/>
答案在此:{
{answer}}<br/>
</div>
</body>
</html>
<script type="text/javascript" src="vue.min.js" ></script>
<script type="text/javascript">
let v1 = new Vue({
el:"#app1",
data:{
question:"",
answer:""
},
watch:{
question:function(){
this.answer="正在查找答案……";
this.getAnswer();
}
},
methods:{
getAnswer:function(){
let thanV = this;
fetch("qa.php?Q="+this.question,{
method:"GET"
})
.then((res)=>{
return res.text();
})
.then((res)=>{
thanV.answer = res;
});
}
}
});
</script>
后端代码(qa.php):
<?php
//1、接收请求参数;
$Q = $_GET['Q'];
if($Q=="你吃的啥"){
echo "草";
}else if($Q=="你挤的啥"){
echo "奶";
}else{
echo "智商欠费,没法回答";
}
?>
还没有评论,来说两句吧...