【问题标题】:VueJS V-bind:sync="{object}" -- watching data emitted from child in parentVueJS V-bind:sync="{object}" -- 在父节点中观察子节点发出的数据
【发布时间】:2019-12-09 05:03:46
【问题描述】:

我正在编写一个应用程序,其中我有一个父组件,它通过v-bind:sync="form" 将对象this.form 传递给子表单组件,子表单为@input 上父的每个键发出值.

我想在父级中查看this.form 的值,但在 v-bind:sync 的情况下,父级上的对象似乎没有反应性,即使在父级中的提交操作上我提交 @ 987654325@ 包含子级发出的所有值。

代码示例 家长:

<ParentComponent>

  <ChildComponent v-bind:sync="form"/>

  {{form}} <--- this doesn't update after child component emits

   <button @click="submit"> submit actions here have access to updated this.form... </button>
</ParentComponent>

...

data() {
  return {
      form: { ...some object keys}
}

【问题讨论】:

  • 您究竟是如何“为@input 上的父级的每个键发出值”?
  • 嗨,Tony,这里是 Vue 文档:组件 $emit 函数/事件,您使用 $emit 将值从子级传递给父级:vuejs.org/v2/guide/components-custom-events.html
  • 我知道$emit。我实际上是在询问您用于将值传递给父级的确切代码,因为问题可能出在那个区域。

标签: javascript vue.js


【解决方案1】:

您可以在观察者中使用deep 来观察对象属性的变化。

类似

  watch: {
    form: {
      handler() {
        console.log('form change')
      },
      deep: true
    }
  },

document

要同时检测对象内部的嵌套值变化,您需要通过 in deep:在 options 参数中为 true。请注意,您不需要这样做 所以要监听 Array 的变化。

我创建了一个demo here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    相关资源
    最近更新 更多