通过 prop 从根组件传递到子组件的 VueJs 数据只会产生一个可观察的对象



我有一个应用程序,它在created()函数中调用Web服务并填充根数据对象的属性。该属性通过 prop 传递给子组件,使用 Chrome 开发工具,我可以看到 prop 数据在子组件上可用。

我遇到的问题是我尝试使用通过属性数据最终得到undefined属性数据的 prop 传递的值在子组件中设置数据属性。如果我使用 Chrome 检查工具并添加断点,我可以看到 prop 是{__ob__: Observer}形式的可观察对象,因此,我无法直接访问任何数据。我怀疑子对象在 Web 服务调用在根目录中完成之前设置了它的数据属性。

我怎样才能克服这个问题?

我为此创建了一个 JsFiddle: https://jsfiddle.net/ProNotion/a8c6nqsg/

Vue.component("mycomponent", {
template: '#my-component-template',
props: ["customer_data"],
data() {
return {
form_data: {
customerEmail: this.customer_data.customerEmail1
}
}
}
});
new Vue({
el: "#app",
data() {
return {
customer: {}
};
},
methods: {
init() {
var self = this;
axios.get("https://0bb1313e-b089-432e-b6bc-250f6162d7f0.mock.pstmn.io/GetCustomerData")
.then(response => {
self.customer = response.data;
}).catch(response => {
console.error(response);
});
}
},
created() {
this.init();
}
});

这是我的 HTML 标记:

<div id="app">
<mycomponent :customer_data="customer" />
</div>
<script type="x-template" id="my-component-template">
<div>
<p>{{form_data.customerEmail1}}</p>
</div>
</script>

检查响应数据类型和格式

console.log(typeof response.data) // string
{ "customerEmail1": "me@example.com", } // Remove `,`

您必须解析为 JSON 类型

axios.get(...).then(response => {
self.customer = JSON.parse(response.data.replace(',', ''))
})

使用"深度"选项设置要监视的属性 [深度观看](https://v2.vuejs.org/v2/api/#vm-watch)将检测对象内部的嵌套值变化 ``` Vue.component("mycomponent", { 模板:"#my 组件模板", 道具:["customer_data"], 数据() { 返回 { form_data: {} } }, 观看:{ customer_data: { 处理程序 (val) { this.form_data = 值; }, 深度:真 } } }); ```演示:https://jsfiddle.net/ghlee/f4gewvqn

最新更新