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

时间:2019-04-05 22:32:00

标签: javascript vue.js components

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

在我的父组件中,单击事件将openModal的值从false设置为true。然后,此值通过prop传递到子组件。然后,在该子组件中,更新后的布尔值应通过类绑定将一个类添加到div,而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.

2 个答案:

答案 0 :(得分:0)

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

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

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

export default {   
  props: {
    modal: Boolean 
  } 
}

答案 1 :(得分:0)

正确。

如果此父/子关系比较复杂,或者您需要向上传递给父/母关系,则还有其他同步选项: