vue学习之计算属性和侦听器、过滤器
程序员文章站
2022-05-17 07:50:41
...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>计算属性和侦听器、过滤器</title>
</head>
<body>
<div id="app">
<!--某些结果是基于之前数据实时计算出来的,我们可以利用计算属性computed来完成-->
<!--watch可以让我们监控一个值的变化,从而作出相应的反应-->
<ul>
<li>西游记:价格:{{xyjPrice}},数量 :<input type="number" v-model="xyjNum" /></li>
<li>水浒传:价格:{{shzPrice}},数量 :<input type="number" v-model="shzNum" /></li>
<li>总计:{{totalPrice}}</li>
{{msg}}
</ul>
</div>
<div id="app2">
<li v-for=" user in userList">
使用局部过滤器:{{user.name}}-> {{ user.gender | genderFilter }}
使用全局过滤器: {{user.name}}-> {{ user.gender | gFilter }}
</li>
</div>
<script src="./node_modules/vue/dist/vue.js"></script>
<script>
//全局过滤器 放前面
Vue.filter("gFilter", function (val) {
if (val == 1) {
return "男";
}
else {
return "女";
}
});
var app1 = new Vue({
el: "#app",
data: {
xyjPrice: 99.99,
xyjNum: 1,
shzPrice: 98.00,
shzNum: 1,
msg: ""
},
computed: {
totalPrice() {
return this.xyjPrice * this.xyjNum + this.shzPrice * this.shzNum;
}
},
watch: {
xyjNum: function (newval, oldval) {
if (newval >= 3) {
this.msg = "西游记库存超出限制,最多还有3";
this.xyjNum = 3;
}
else {
this.msg = "";
}
}
}
});
var app2 = new Vue({
el: "#app2",
data: {
userList: [
{ name: "aa", gender: "0" },
{ name: "bb", gender: "1" }
]
},
//局部过滤器
filters: {
genderFilter(val) {
if (val == 1) {
return "男";
}
else {
return "女";
}
}
}
});
</script>
</body>
</html>