Vue.js - 如何在数据对象发生变化时发送给父组件?

标签 vue.js vue-component two-way-binding v-model vue-data

使用v-model 在组件内的 View 和数据模型之间创建双向绑定(bind)。 View 交互可以向父组件发出事件。

但是,子组件中的数据模型更改是否可以向父组件发出事件?

因为只要用户单击复选框,父级和子级中的情况都很好(数据模型更新并且事件被发出)。但是,如果我打开 Vue 开发工具并切换子组件数据中的复选框,来自 v-model 的双向绑定(bind)将在子组件中进行适当的更新,但没有任何效果它传递给父组件(我怀疑是因为没有发出事件)。

如何确保父组件“知道”子组件中的数据更改?我认为这在某种程度上是可能的...如果不是从子组件发出,也许有某种方法可以让父组件“监视”子组件的数据?

感谢您的帮助或指导!同时我会继续阅读并寻找答案!

子组件

<template>
  <div class="list-item" v-on:click="doSomething">
    <input type="checkbox" v-model="checked">
    <label v-bind:class="{ checked: checked }">{{ name }}</label>
  </div>
  ...
</template>

<script>
  ...
  data: function() {
    return {
      checked: false,
    }
  },
  methods: {
    doSomething() {
      ...
      this.$emit('doSomething', this)
    }
  }
</script>

父组件

<template>
  <ChildComponent v-on:doSomething="getItDone"></ChildComponent>
  ...
</template>

<script>
  ...
  methods: {
    getItDone(target) {
      ...
    }
  }
</script>  

更新:在对 @IVO GELOV 的解决方案进行了更多研究之后,我现在遇到的问题是,当涉及多个子组件时,由于父组件的 myBooleanVar 的单一值驱动整个事情,选中一个子组件的框会导致所有子组件被选中。

因此, View 和数据操作都将其转移给父级,这绝对是进步,但我仍在尝试找出如何“隔离”这种情况,以便仅拖动所操作的一个子组件参加聚会...

最佳答案

您可以将数据保留在父级中,将其作为 Prop 提供给子级,让子级观看 Prop 并更新其内部状态,最后当子级的内部状态已完成时向父级发出事件改变了。

父级

<template>
  <ChildComponent v-model="myBooleanVar" />
  ...
</template>

<script>
  data()
  {
    return {
      myBooleanVar: false,
    }
  },
  watch:
  {
    myBooleanVar(newValue, oldValue)
    {
      if (newValue !== oldValue) this.getItDone(newValue);
    }
  },
  methods: 
  {
    getItDone(value) 
    {
      ...
    }
  }
</script>  

child

<template>
  <div class="list-item">
    <input type="checkbox" v-model="checked">
    <label :class="{ checked: checked }">{{ name }}</label>
  </div>
  ...
</template>

<script>
  props:
  {
    value:
    {
      type: Boolean,
      default: false
    }
  }
  data() 
  {
    return {
      checked: this.value,
    }
  },
  watch:
  {
    value(newVal, oldVal)
    {
      // this check is mandatory to prevent endless cycle
      if(newVal !== oldVal) this.checked = newVal;
    },
    checked(newVal, oldVal)
    {
      // this check is mandatory to prevent endless cycle
      if(newVal !== oldVal) this.$emit('input', newVal);
    }
  },
</script>

关于Vue.js - 如何在数据对象发生变化时发送给父组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63975787/

相关文章:

javascript - 如何从双向绑定(bind)表单输入控件访问先前的值?

javascript - 将 Angular4 中的 [ngStyle] 绑定(bind)到 ngModel 或 2 路绑定(bind)

javascript - 访问 Vuejs 组件内的元素

javascript - 在Vuejs中显示数据

javascript - vue webpack 模板(通过 vue-cli)以后会变得更容易使用吗?

javascript - Vue for 循环内的绑定(bind)元素无法正常工作

twitter-bootstrap - 如果在框列表上单击,如何添加选定的按钮?

javascript - Vue.js 挂载方法被调用两次

javascript - 如何将 TextToSpeech.talk ("hi' ) 操作添加到按钮

Angular 12 - 双向绑定(bind)给出错误 : The property and event halves of the two-way binding 'prop_name' are not bound to the same target