【问题标题】:VueJs Data Passed From Root to Child Component via Prop Results in only an observable object通过 Prop 从根传递到子组件的 VueJs 数据仅产生一个可观察的对象
【发布时间】:2019-12-31 07:19:22
【问题描述】:

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

我遇到的问题是我尝试使用通过 prop 传递的值在子组件中设置数据属性,最终得到undefined 属性数据。如果我使用 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>

【问题讨论】:

  • 试试&lt;p&gt;{{ customer_data.customerEmail1 }}&lt;/p&gt;。问题是customerEmail: this.customer_data.customerEmail1 只运行一次并且没有分配引用,所以当customer_data 更新时,您的customerEmail 属性不是
  • 不幸的是,我的示例被简化了,我需要根据来自父级的数据设置 form_data 的初始值,但稍后可以更改它们,因为这些值将绑定到表单字段。您的建议适用于演示数据,但不幸的是无法解决我对可编辑数据的问题。如果我理解正确,您所描述的就是我所怀疑的,那么我该如何延迟数据的分配,直到 API 调用填充父属性?
  • @Phil 我想我可以为customer_data 配置一个手表并为form_data 设置数据值但是如果父数据由于某种原因应该更改,它将覆盖对子组件数据的任何更改?

标签: vue.js vuejs2 vue-component


【解决方案1】:

检查响应数据类型和格式

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

必须解析为 JSON 类型

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


使用deep 选项设置要观看的属性

Deep watching 将检测对象内部的嵌套值变化

Vue.component("mycomponent", {
  template: '#my-component-template',
  props: ["customer_data"],
  data() {
    return {
      form_data: {}
    }
  },
  watch: {
    customer_data: {
      handler (val) {
        this.form_data = val;
      },
      deep: true
    }
  }
});

演示: https://jsfiddle.net/ghlee/f4gewvqn

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多