监听函数和计算函数:
面试题:
监听函数和计算函数的区别:
#### 监听函数只监听一个变量,计算函数可计算多个变量。
#### 监听函数是异步函数,计算函数是同步函数。
#### 监听函数不具有缓存性,页面重新渲染,值不发送变化,也会执行;
#### 计算函数具有缓存性,页面重新渲染,值不发生变化,但会返回之前的结果。
计算函数computed
调用时不需要()
姓:<input type="text" v-model="a"><br>
名:<input type="text" v-model="b"><br>
<span>{{fullname}}</span>
computed:{
fullname:function(){
return this.a + this.b;
}
}
监听函数watch
#### 监听函数中的函数名必须和监听变量名一致
参数固定news,old // count:function(news,old){
调用时不需要()
<input type="button" value="计算" @click="count++">
<span>{{count}}</span>
new Vue({
el:"#app",
data:{
count:0,
},
watch:{
count:function(news,old){
if(news >= 6)
this.count = 6;
}
},
})
过滤函数filters
<input type="text" v-model="str"><br>
<span>{{str|strfun}}</span>
new Vue({
el:"#app",
data:{
str:"a"
},
filters:{
strfun:function(value){
return value.toUpperCase();
}
},
})
举例:
<body>
<div id="app">
姓:<input type="text" v-model="a"><br>
名:<input type="text" v-model="b"><br>
<span>{{full}}</span>
<hr>
<input type="button" value="计算" @click="count++">
<span>{{count}}</span>
<hr>
<input type="text" v-model="str"><br>
<span>{{str|strfun}}</span>
</div>
<script>
var v = new Vue({
el:"#app",
data:{
a:"",
b:"",
count:0,
str:"a",
},
filters:{
strfun:function(value){
return value.toUpperCase();
}
},
methods:{
},
watch:{
count:function(news,old){
if(news >= 6)
this.count = 6;
}
},
computed:{
full:function(){
return this.a + this.b;
}
},
})
console.log(v.str)
</script>
</body>