VUe computed 和watch的使用

Vue中computed就是 实时计算 使用。
Vue检测到数据发生变动时就会执行对相应数据有引用的函数。
下面是一个demo。引用自己的vue.js就可以看效果。
利用computed可以做一些监控之类的效果。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1,IE=edge">
<title>title</title>
<link href="" rel="stylesheet">
<script src="js/vue.js"></script>
</head>
<body>
<template id="vue">
<input type="text" v-model="name" />
<label v-for="cb in inputs">
<input type="checkbox" value="{{cb.value}}" v-model="checkbox" />{{cb.name}}
</label> <br>
<div> <!--下面2个是一样的效果-->
{{checkbox||json}}<br>
{{getCheckBoxes}}<br>
</div>
<div><!--下面2个是一样的效果-->
{{getName}}<br>
{{name}}
</div>
</template>
</body>
<script type="text/javascript">
var inputs = ['JAVA','C#','RUBY'].map(function (el,index) {
return {value:index,name:el};
});
var vm= new Vue({
el:'#vue',
data:{
name:'testName',
inputs:inputs,
checkbox:['0']
},
watch:{
//检测属性变化
'name':function(newValue,oldValue){
console.log('name has changed ',newValue,oldValue);
}
},
computed:{
getCheckBoxes:function(){
console.log('run getCheckBoxes');
return this.checkbox.join(',');
},
getName:function(){
console.log('run getName');
this.checkbox.join(',');
console.log("getName use checkbox");
return this.name;
}
}
});
</script>
</html>

猜你喜欢

转载自blog.csdn.net/ToBeBestPlayer/article/details/82800814