<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./lib/vue.min.js"></script>
</head>
<body>
<div id="box">
<p>{{fullname}}</p>
<p>{{age}}</p>
</div>
<script>
var vm = new Vue({
el: '#box',
data: {
firstname: "hello",
lastname: "kit",
age: 25
},
computed:{
//写成对象格式
fullname:{
get:function(){
return this.firstname+" "+this.lastname
},
set:function(newValue){
var names=newValue.split(' ')
this.firstname=names[0]
this.lastname=names[names.length-1]
}
}
}
});
</script>
</body>
</html>
通过调试发现,给fullname赋值一个新值,setter方法会被调用,firstname和lastname的值都会发生改变