computed
定义:要用的属性不存在,要通过已有的属性来计算得来。
原理
- get
- set
代码示例
javascript
computed:{
fullName:{
// 当读取fullName,get会被调用,且返回值就作为fullName的值(有缓存)
// get什么时候被调用,初次读取fullName时,所依赖的数据发生变化时。
get(){
console.log("get被调用了")
// 此处的this是vm
// 此处不能写vm,只能写this
return this.firstname+" - "+this.lastname
},
// set什么时候被调用? 当fullName被修改时。
set(value){
console.log('set',value)
// 字符串拆分
const arr = value.split('-')
this.firstname = arr[0]
this.lastname = arr[1]
}
}
}计算属性的简写
只有当计算属性只用来读取而不修改时才能使用简写
javascript
computed: {
fullName() {
console.log("get被调用了")
return this.firstname + " - " + this.lastname
}
}