<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="plug-in/vue.js"></script>
<title>Title</title>
</head>
<body>
<div class="app">
<H3>{{fullName}}</H3>
<button @click="changeName">Change</button>
</div>
</body>
<script>
var app = new Vue({
el: '.app',
data: {
firstName: 'Foo',
lastName: 'Bar',
// fullName:'Full Bar',
},
methods:{
changeName:function(){
this.fullName = 'Full Bar'
}
},
// computed:{
// getter方法
// fullName(){
// return this.firstName +' ' + this.lastName
// }
// }
computed: {
fullName: {
get: function () {
return this.firstName + '-' + this.lastName
},
set:function(newValue) {
console.log(newValue); // newValue是改变后的值
var names = newValue.split(' ');
this.firstName = names[0];
// this.lastName = names[1]; // 当firstName和lastName中间有多个空格时会出问题
this.lastName = names[names.length-1];
console.log(this.firstName);
console.log(this.lastName);
}
}
}
})
</script>
</html>
计算属性的执行顺序:
1.{{fullName}} 首先会执行get:function(),渲染出结果(Foo-Bar)。
2.当单击Change按钮时,会触发changeName函数,{{fullName}}变为'Full Bar',这时会触发set:function(newValue),newValue就是改变后的
fullNmae('Full Bar'),经过split()等一系列的处理之后,firstName=Full,lastName=Bar。
3.最后执行get:function()渲染出结果(Full-Bar)。