繁体   English   中英

当父组件更改 prop(布尔值)时,子组件不更新

[英]child component not updating when prop (boolean) is changed by parent component

当我更改父 Vue 组件中的 props 值(布尔值)时,子组件不会更新以触发模态打开。

在我的父组件中,单击事件将 openModal 的值从 false 设置为 true。 然后这个值通过一个 prop 向下传递到一个子组件。 在该子组件中,更新后的布尔值应该通过类绑定将一个类添加到一个 div,作为回报,它会打开一个模态。

父组件:

<FilmListItem
      v-for="slice in slices"
      @click.native="openModal=true"
    />

<child-component :modal="openModal">
...

data() {
  return {
    openModal: false
  }
}

子组件:

<div
    class="modal__container"
    :class="{ 'modal--show': showModal }">
...
export default {
  props: {
    modal: Boolean
  },
  data() {
    return {
      showModal: this.modal
    }

In the vue dev tools I can see, that the value of the prop changes in the parent. Yet, my child component doesn't update. It worked when I forced the child component to reload when I was assigning a new :key value together with changing the Boolean. But that feels a little hacky to me. Also, a watcher within the child component didn't do the trick. It simply wouldn't watch the changed prop value. Any ideas very much appreciated. Thanks in advance.

我实际上现在自己找到了解决方案:

在子组件中,我试图通过数据对象访问props的数据。 但我只是直接访问道具的数据:

<div   
  :class="{ 'modal--show': modal }"> 
...

export default {   
  props: {
    modal: Boolean 
  } 
}

正确的。

如果此父/子关系更复杂,或者您需要向上传递回父级,则其他同步选项:

  • 将 :modal 值放在 Vuex 存储中,并在子组件上使用计算属性。

  • 使用 EventBus: https ://alligator.io/vuejs/global-event-bus/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM