computed&watch&method
计算属性的getter&setter方法
computed: {
fullName: {
get: function() {//默认的getter方法
return this.firstName + ' ' + this.lastName
},
set: function(value) {//fullName改变时setter被调用
var names = value.split('')
this.firstName = names[0]
this.lastName = names[names.length - 1]
}
}
}
computed&method
计算属性:优化模板表达式
data: {
msg: '123'
}
//msg改变才会重新求值,不改变会立即返回之前的结果
computed: {
reverseMsg: function() {
return this.msg.split('').reverse().join('')//'321'
}
}
arr.reverse()//reverse方法反转数组
arr.join(separator)//数组转换为字符串,传参指定分隔符
//只要调用就会执行
methods: {
reverseMsg: function() {
return this.msg.split('').reverse().join('')
}
}
computed&watch
data: {
firstName: 'First',
lastName: 'Last',
fullName: 'First Last'
},
watch: {
firstName: function(val) {
this.fullName = val + ' ' + this.lastName
},
lastName: function(val) {
this.fullName = this.firstName + ' ' + val
}
}
//计算属性更方便
computed: {
fullName: function() {
return this.firstName + ' ' + this.lastName
}
}
watch
- 在数据变化时执行异步
- 开销较大操作时使用