我有一个绑定在对象上的组件,父组件更改其对象的属性。子组件应该对更改做出反应。
子组件:
import { Component, Emit, Inject, Model, Prop, Provide, Vue, Watch } from 'vue-property-decorator'
@Component({
props: {
value: Object,
}
})
class ValidatedSummaryComponent extends Vue {
value: any;
field = "Name";
v: any;
created() {
console.log("!", this.value);
this.v = this.value;
}
state: string | null = null;
error = "";
@Watch('value')
onValueChanged(val: any, oldVal: any) {
console.log("Value called", val);
this.v = val;
this.onChanged();
this.$forceUpdate();
}
private onChanged() {
if (typeof this.v.validationErrors[this.field] == 'undefined') {
this.state = null;
this.error = "";
} else {
this.state = 'invalid';
this.error = this.v.validationErrors[this.field].join();
}
}
}
export default ValidatedSummaryComponent;
用法:
<ValidatedSummary v-bind:value="bindableObject"></ValidatedSummary>
然后我会:
bindableObject.Name = 'New name'
我需要我的组件
ValidatedSummaryComponent
做出反应。
我可以把它作为一个单独的属性绑定:
<ValidatedSummary v-bind:value="bindableObject.Name"></ValidatedSummary>
,但是
在最终设计中,组件应该注意
BindableObject
会有一些不同的
BindableObjects
有不同的属性集,所以我不能一个属性一个属性地绑定它。
我设法使其工作的唯一方法是强制vue.js更新整个对象,以确保vue.js相等检查不通过:
this.bindableObject = Object.assign(new BindableObject(), this.bindableObject );
但这是非常麻烦的,因为我将不得不这样做的每一个变化,所以我正在寻找一个更好的方式来处理这一点。
把它移走也不错
this.$forceUpdate();
在上面的代码中,但我可以存活下来。