computed的属性不仅可以写一个get方法,通过其他的值算出一个新值;同时,也可以设置set方法,通过设置一个值,来改变他相关联的值!而改变了相关联的值之后,又会引起fullName的重新计算,页面也会跟着显示新的内容!
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>计算属性的setter和getter</title><!--引入vue.js库--><script src="../vue.js"></script>
</head><body>
<!--vue接管的div-->
<div id="root">
</div><script>var vm = new Vue({el: '#root',data: {firstName: "gb",lastName: "lfy"},computed: function () {fullName: function f() {return this.firstName +" "+ this.lastName();}}});
</script>
</body>
</html>
computed属性:
当computed依赖的值发生变化时,他就会重新计算;当set函数中this.firstName和 this.lastName 是fullName依赖的值;属性变了,页面的内容也会跟着变化!
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>计算属性的setter和getter</title><!--引入vue.js库--><script src="../vue.js"></script>
</head><body>
<!--vue接管的div-->
<div id="root">{{fullName}}
</div><script>var vm = new Vue({el: '#root',data: {firstName: "gb",lastName: "lfy"},computed: {fullName: {get: function () {return this.firstName + this.lastName();},set: function (value) {// console.log(value);var arr = value.split(" ");this.firstName = arr[0];this.lastName = arr[1];}}}});
</script>
</body>
</html>