监听属性可以针对某个属性进行监听,只要这个属性的值发生改变了,那么就会执行相应的函数。示例代码如下
<div id="app">
<div>
<label>搜索:</label>
<input type="text" name="keyword" v-model:value="keyword">
</div>
<div>
<p>结果:</p>
<p>{{answer}}</p>
</div>
</div>
<script>
let vm = new Vue({
el: "#app",
data: {
keyword: "",
answer: ""
},
watch: {
keyword: function(newKeyword,oldKeyword){
this.answer = '加载中...';
let that = this;
setTimeout(function(){
that.answer = that.keyword;
},Math.random()*5*1000);
}
}
});
</script>
网友评论