【问题标题】:child component not updating when prop (boolean) is changed by parent component父组件更改道具(布尔值)时子组件不更新
【发布时间】:2019-08-27 20:59:02
【问题描述】:

当我更改父 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.

【问题讨论】:

    标签: javascript vue.js components


    【解决方案1】:

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

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

    <div   
      :class="{ 'modal--show': modal }"> 
    ...
    
    export default {   
      props: {
        modal: Boolean 
      } 
    }
    

    【讨论】:

      【解决方案2】:

      正确。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-30
        • 2018-08-09
        • 1970-01-01
        • 2018-07-02
        • 2021-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多