Vue Computed属性get、set不生效?
vue computed的get、set不生效,会是什么问题呢?
export default { props: {
endPoint: {
type: Object
}
},
computed: {
nativeEndPoint: {
get() {
console.log('-----获取--', this.endPoint)
return {
...this.endPoint
};
},
set(endPoint) {
console.log('----------更新')
}
}
}
}
<input v-model="nativeEndPoint.width"/><input v-model="nativeEndPoint.height/>
传入endPoint值:width: 100, height: 100}
如上图所示,当输入框修改值时,无法触发set()函数,实在奇怪,有没有大佬懂的
回答:
<input v-model="endPointWidth"/><input v-model="endPointHeight"/>
export default { props: {
endPoint: {
type: Object
}
},
computed: {
endPointWidth: {
get() {
return this.endPoint.width;
},
set(newWidth) {
this.$emit('update:endPoint', { ...this.endPoint, width: newWidth });
}
},
endPointHeight: {
get() {
return this.endPoint.height;
},
set(newHeight) {
this.$emit('update:endPoint', { ...this.endPoint, height: newHeight });
}
}
}
}
属性多的话:
export default { props: {
endPoint: {
type: Object
}
},
computed: {
...generateComputedProperties(['width', 'height', 'depth', 'color'])
}
}
function generateComputedProperties(props) {
let computed = {};
props.forEach(prop => {
computed[`endPoint${capitalizeFirstLetter(prop)}`] = {
get() {
return this.endPoint[prop];
},
set(value) {
this.$set(this.endPoint, prop, value);
}
};
});
return computed;
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
回答:
因为你修改的是“属性的属性”,而不是“属性”,所以会出现这种情况。
以上是 Vue Computed属性get、set不生效? 的全部内容, 来源链接: utcz.com/p/935216.html