计算属性:
依赖对象(一般是vue变量的某个属性值),set函数,get函数,缓存。
set函数:
- 当该依赖属性的值被改变时触发该函数,修改过后的值可被当作参数传入该函数。(如下例中的参数:newPassword ,即为修改后的值)
get函数:
- 该依赖属性被调用的时候触发该函数。(computed默认只提供该函数即在computed中写的函数默认为get类型的函数,如需补充set函数还需自行补充)。
- 每次 get函数返回的值即为该 依赖属性 的值。
缓存:
- 当需要多次调用computed时,只要所依赖的 “属性值” 不发生变化,就无需重新调用执行。(区别于函数调用,每次调用都需重新执行)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>
</head>
<style>
</style>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<body>
</body>
<script>
var vm = new Vue({
el: "#app",
data: {
use: false,
textChange: true,
info: 'hahah',
update: false,
},
computed: {
password: {
set: function(newPassword){
this.update=true;
this.info = newPassword.toUpperCase();
console.log("我是setter函数");
},
get: function(){
var result = this.update ? '密码已经被修改':'密码未被修改';
console.log("我是getter函数");
return result + ' '+'密码:'+this.info;
// return this.password; 如此返回出现死循环
}
}
}
});
console.log(vm.password)
vm.password = 'hhy';
console.log(vm.password);
</script>