1
votes

I'm new to Vue and I'm struggling to pass dynamic data from parent to child component through props. My parent component should pass a boolean (isModalVisible) to a children component through the visible prop. In the parent, the isModalVisible changes (from false to true) when the button is clicked. But the child component keeps the initial value. As far as I have understood, the data() is executed when the component is created and when any value that has been bound (visible, in this case) is changed, but this does not occurs. Anyone can help me to find out what I am missing?

Parent component:

<template>
<div>
   {{ isModalVisible }}
   <CoursesModal :visible="isModalVisible" />
   <button @click="showModal" title="Courses">
      Courses
   </button>
</div>
</template>
<script>
import CoursesModal from "../components/modals/Courses.vue";
export default {
  components: {
    CoursesModal
  },
  data() {
    return {
      isModalVisible: false
    };
  },
  methods: {
    showModal() {
      this.isModalVisible = true;
    },
    closeModal() {
      this.isModalVisible = false;
    }
  },
};
</script>

Child (modal) component:

<template>
  <div>
    {{ visible }}
  </div>
</template>

<script>
export default {
  components: {
    props: {
      visible: {
        type: Boolean,
        default: true
      }
    }
  },

  data: function() {
    return {
      visible: false,
    };
  }
};
</script>

I have tried, too, to do

return {
   visible: this.visible,
};

but this value is undefined.

My package.json:

"dependencies": {
   "core-js": "^3.9.1",
   "nuxt": "^2.15.3"
}
1
if you have a prop named visible don't keep a data property with exact name. only use the prop value, you don't need that data property in child componentTowkir
Also, when your prop changes, your data property shouldn't change, you can directly use the prop value to watch for changes, and act accordingly.Towkir
@Towkir I tried to remove the data function but then the compiler throws an error "Property or method "visible" is not defined on the instance but referenced during render"Christian Benseler

1 Answers

3
votes

I think you make a mistake about the components property. The components property did not have props property and it is used to register the component. You can read further here and here

Here is the correct way to use props:

<template>
  <div>
    {{ visible }}
  </div>
</template>

<script>
export default {
  // removed the components and data property
  props: {
    visible: {
      type: Boolean,
      default: true
    }
  }
};
</script>