计算属性
复杂逻辑,模板难以维护
(1) 基础例子
(2) 计算缓存 VS methods
-计算属性是基于它们的依赖进行缓存的。
-计算属性只有在它的相关依赖发生改变时才会重新求值
(3) 计算属性 VS watch
- v-model
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Examples</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
<script src="lib/vue.js"></script>
</head>
<body>
<div id="box">
{{ myname.substring(0,1).toUpperCase()+ myname.substring(1) }}
<br/>
计算属性11111:{{ mycomputedname }}
<br/>
方法111111: {{ mycomputedmethod() }}
<br/>
计算属性2222:{{ mycomputedname }}
<br/>
方法222222: {{ mycomputedmethod() }}
</div>
<script type="text/javascript">
var vm = new Vue({
el:"#box",
data:{
myname:"kerwin"
},
methods:{
mycomputedmethod(){
console.log("方法mycomputedmethod")
return this.myname.substring(0,1).toUpperCase()+ this.myname.substring(1)
}
},
computed:{
//定义一个计算属性
mycomputedname(){
//1.必须有返回值
//2. 每次依赖改变 ,计算属性会重新计算一下
//3. 缓存(内存)
console.log("计算属性mycomputedname")
return this.myname.substring(0,1).toUpperCase()+ this.myname.substring(1)
}
}
})
</script>
</body>
</html>
计算属性vswatch-watch
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Examples</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
<script src="lib/vue.js"></script>
</head>
<body>
<div id="box">
<!-- <button @click="handleClick()">登录</button> -->
单价<input type="text" v-model="myprice" />
数量<input type="text" v-model="mynumber" />
<p>{{sum}}</p>
</div>
<script type="text/javascript">
var vm = new Vue({
el:"#box",
data:{
myprice:100,
mynumber:1,
sum:0
},
watch:{
myprice(){
console.log("price改变",this.myprice)
if(this.mynumber*this.myprice>1000){
this.sum = this.mynumber*this.myprice;
}else{
this.sum = this.mynumber*this.myprice+100;
}
},
mynumber(){
console.log("number改变",this.mynumber)
if(this.mynumber*this.myprice>1000){
this.sum = this.mynumber*this.myprice;
}else{
this.sum = this.mynumber*this.myprice+100;
}
}
}
})
/*
1. @input = "handleInput" 默认传事件对象
2. @input = "handleInput($event)" 传事件对象
3. v-model 双向数据绑定指令 -> mvvm (双向数据绑定) ,作用于 表单元素
双向绑定是 value(checked) <-----> 状态
4. data 中定义 key值 叫 状态。
*/
</script>
</body>
</html>

Comments | NOTHING