文章目录
计算属性和侦听器过滤器
计算属性和侦听器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</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>
<scrIpt src="../node_modules/vue/dist/vue.js"></scrIpt>
<script>
let vm = new Vue({
el:"#app",
data:{
xyjPrice: 99.9,
shzPrice: 88.9,
xyjNum:1,
shzNum:1,
limitNum:3,
msg:""
},
computed: {
totalPrice() {
return this.xyjPrice*this.xyjNum+this.shzPrice*this.shzNum;
}
},
watch: {
xyjNum(newVal,oldVal) {
if(newVal >= this.limitNum) {
this.msg = "西游记超出库存数量";
this.xyjNum = 3
} else {
this.msg = ""
}
},
//也可以用这种声明方法shzNum:function(newVal,oldVal) ,一般用第一种shzNum(newVal,oldVal),
shzNum:function(newVal,oldVal) {
if (newVal >= this.limitNum) {
this.msg = "水浒传超出库存数量";
this.shzNum = 3
} else {
this.msg = ""
}
}
},
})
</script>
</body>
</html>
过滤器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 过滤器常用来处理文本格式化的操作。过滤器可用在两个地方:双花括号插值和v-bing 表达式 -->
<div id = "app">
<ul>
<!-- 局部过滤器 -->
<li v-for="user in userList">
{{user.id}} ===> {{user.gender == 1?"男":"女"}} ==》 {{user.gender | genderFilter}}
</li>
<br>
<!-- 全局过滤器 -->
<li v-for = "user in userList">
{{user.gender | gFilter}}
</li>
</ul>
</div>
<script src="../node_modules/vue/dist/vue.js"></script>
<script>
// 可以定义全局过滤器代替局部过滤器
Vue.filter("gFilter",function(val){
if (val == 1) {
return "男~~~"
} else {
return "女~~~"
}
})
let vm = new Vue({
el:"#app",
data:{
userList:[
{id:1,name:"小杨",gender:1},
{id:2,name:"小红",gender:0}
]
},
filters:{
//filters 定义局部过滤器,只可以在当前vue实例中使用
genderFilter(val) {
if (val == 1) {
return "男";
} else {
return "女";
}
}
}
})
</script>
</body>
</html>