计算属性computed,对数据进行处理,生成一个新属性,计算属性要return
//watch监听属性 监听属性变化 传入两个参数 一个newValue(新值),一个(oldValue)旧值
案例如下:
<!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="myapp">
<!-- 总价提交到后台 {{number*price用一个变量报错}}-->
商品数量:{{number}}</br> 商品价格:{{price}}</br> 商品总价{{total}}</br>
<button @click='addBtn'>添加</button>
<input type="text" v-model='txt'>
</div>
</body>
</html>
</body>
<script src="../vue.js"></script>
<script>
new Vue({
el: '#myapp',
data: {
number: 10,
price: 5,
// total: this.number * this.price;//计算的总价不能在此处写否则NaN,应该放在计算属性里面 存在很大问题
txt: 'input框默认值'
},
computed: { //计算属性computed,对数据进行处理,生成一个新属性,计算属性要return
total() {
return this.number * this.price;
}
},
watch: { //watch监听属性 监听属性变化
txt(newValue, oldValue) { //也可以txt:function(newValue,oldValue){}
console.log(newValue);
console.log(oldValue);
}
},
methods: {
addBtn() {
this.number++; //没改变一次数量商品加1
}
},
})
</script>