Vue.js:从子组件更新props,但props不会立即更改?

huangapple go评论79阅读模式
英文:

Vuejs: update props from children component but props does not change instantly?

问题

我正在尝试使用 this.$emit('updateData', data); 从子组件更新一个属性值,当我在父组件中记录接收到的数据时,它确实发生了变化。但是当我在子组件中记录它时,它没有发生变化。以下是我的代码:

<child :propDataFromParent="someData"></child>

props: ['propDataFromParent'],
methods: {
   updateData(data) {
      this.$emit('updateData', data);
      console.log(this.propDataFromParent);
   }
}

我尝试过使用谷歌搜索,并使用 ChatGPT,但没有帮助。

英文:

I'm trying to update an prop value from a child component using this.$emit('updateData', data); when i log the data received in parent component, it did changed. But when i logged it out in my child component it didn't change. Here is my code:

&lt;child :propDataFromParent=&quot;someData&quot;&gt;&lt;/child&gt;

props: [&#39;propDataFromParent&#39;]
methods: {
   updateData(data) {
      this.$emit(&#39;updateData&#39;, data);
      console.log(this.propDataFromParent);
   }
}

I tried google search, and use chatgpt but it not helping.

答案1

得分: 2

在Vue中,this.$emit是异步的。如果你在调用this.$emit后立即打印更新后的值,可能看不到更新后的值。

原因是在Vue中,父组件通过监听子组件发出的事件来接收数据。当你调用this.$emit('updateData', data)时,Vue会在当前代码块执行完毕后触发父组件中的事件处理程序。

如果你想在console.log中打印更新后的值,可以使用Vue提供的$nextTick方法。它在DOM更新后执行回调函数,确保在更新完成后打印值。

以下是修改后的代码示例:

methods: {
  updateData(data) {
    this.$emit('updateData', data);

    this.$nextTick(() => {
      console.log(this.propDataFromParent);
    });
  }
}
英文:

In Vue, this.$emit is asynchronous. If you immediately print the updated value after calling this.$emit, you may not see the updated value.

The reason is that in Vue, the parent component listens to events emitted by the child component to receive data. When you call this.$emit(&#39;updateData&#39;, data), Vue will trigger the event handler in the parent component after the current code block has finished executing.

If you want to print the updated value in the console.log, you can use the $nextTick method provided by Vue. It executes a callback function after the DOM has been updated. This ensures that the value is printed after the update is complete.

Here is the modified code example:

methods: {
  updateData(data) {
    this.$emit(&#39;updateData&#39;, data);

    this.$nextTick(() =&gt; {
      console.log(this.propDataFromParent);
    });
  }
}

huangapple
  • 本文由 发表于 2023年6月6日 15:03:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76412157.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定