【发布时间】:2020-11-12 04:55:38
【问题描述】:
在我的子组件中,我的数据中有这个对象:
export default {
name: 'BillingStripeForm',
components: {
Alert
},
data() {
return {
paymentFormError: {},
}
...
}
在这个子组件中,我使用另一个组件根据条件显示错误消息:
<Alert v-if="paymentFormError.description" :description="paymentFormError.description" :title="paymentFormError.title" type="error"></Alert>
表单逻辑由父组件提交。
由于我需要孩子的数据,我给了它一个ref:
<billing-stripe-form ref="billingForm">
当我提交表单时,我通过refs 获取组件及其数据:
let billingFormComponent = this.$refs.billingForm;
现在我将像这样操作孩子的数据:
billingFormComponent.paymentFormError.description = "some error";
billingFormComponent.paymentFormError.title = "Oops! Something went wrong.";
// called on form submit
submitForm() {
let billingFormComponent = this.$refs.billingForm;
let billingAccount = billingFormComponent.billingForm;
let stripe = billingFormComponent.stripe;
let stripeElements = billingFormComponent.stripeElements;
// just testing errors regardless
billingFormComponent.paymentFormError.description = "some error";
billingFormComponent.paymentFormError.title = "Oops! Something went wrong.";
}
从上面看,如果对象具有我刚刚设置的 description,则会显示我的 Alert。
在 vue 开发工具中,我可以看到数据正在正确更改。子组件数据反映了我的 submitForm 函数将其更改为的内容。但是 DOM 没有更新。 Alert 未显示。
如果我刷新页面并通过 Vue 开发工具手动添加数据,我的警报会显示。
那么我怎样才能通过父级上的refs 更新孩子的数据,并让它具有反应性并更新 DOM?
【问题讨论】:
-
你试过 Vue.set(billingFormComponent.paymentFormError, 'description', 'some error') 吗?
-
成功了,谢谢!不知道
Vue.set -
如果您想留下答案,我可以选择您的最佳答案
-
没问题,谢谢伙计!
标签: vue.js