前面介绍了计算属性的基本用法,也提到过,计算属性默认只有 getter,如果我们需要 setter 方法怎么办呢?Vue.js 允许我们手动指定 getter 和 setter 方法,例如:
var app = new Vue({
el: "#app",
data: {
firstName: 'Foo',
lastName: 'Bar',
fullName: 'Foo Bar'
},
computed: {
fullName: {
// getter 方法
get: function () {
return this.firstName + ' ' + this.lastName
},
// setter 方法,参数 newValue 为新的值
set: function (newValue) {
var names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[names.length - 1]
}
}
}
});你可以打开浏览器的控制台,修改例子中的 app.fullName = 'John Doe' 时,setter 会被调用,app.firstName 和 app.lastName 也会相应地被更新。
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue</title>
<!-- 使用 CDN 引入 Vue 库 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
<div id="app">
<div id="demo">{{ fullName }}</div>
</div>
<script type="text/javascript">
var app = new Vue({
el: "#app",
data: {
firstName: 'Foo',
lastName: 'Bar'
},
computed: {
fullName: {
// getter
get: function () {
return this.firstName + ' ' + this.lastName
},
// setter
set: function (newValue) {
var names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[names.length - 1]
}
}
}
});
</script>
</body>
</html>运行效果图:
