vue学习:计算属性computed,侦听器watch,过滤器filters
- computed和watch
computed用来计算总价,watch用来控制库存数量不能超过3:
<div id="app">
<ul>
<li>西游记;价格:{{xyjPrice}},数量:<input type="number" v-model="xyjNumber"></li>
<li>水浒传;价格:{{shzPrice}},数量:<input type="number" v-model="shzNumber"></li>
<li>总价:{{sumPrice}}</li>
<span>{{msg}}</span>
</ul>
</div>
<script src="../node_modules/vue/dist/vue.js"></script>
<script>
new Vue({
el: '#app',
data:{
xyjPrice:99.8,
shzPrice:96,
xyjNumber:1,
shzNumber:1,
msg:""
},
computed:{
sumPrice(){
return this.xyjPrice*this.xyjNumber+this.shzPrice*this.shzNumber;
}
},
watch:{
xyjNumber(newValue,oldVaue){
if(newValue >= 3){
this.msg="库存超出数量";
this.xyjNumber = 3;
}else{
this.msg="";
}
}
}
});
</script>
- filters
全局过滤器:
Vue.filter(“过滤器名”,function(参数){…})
局部过滤器:只能在当前Vue实例中使用
<div id="app">
<ul>
<li v-for="user in userList">
{{user.id}} ===> {{user.name}} ===> {{user.gender | genderFilter}} ===> {{user.gender | gFilter}}
</li>
</ul>
</div>
<script src="../node_modules/vue/dist/vue.js"></script>
<script>
Vue.filter("gFilter",val=>{
if(val==1){
return "男~~~~~";
}else{
return "女~~~~~";
}
})
new Vue({
el: '#app',
data:{
userList:[
{id:1,name:'张三',gender:1},
{id:2,name:'李四',gender:0},
]
},
filters:{
genderFilter (val){
if(val==1){
return "男";
}else{
return "女";
}
}
}
});
</script>