Home > Enterprise >  Pass dynamic props to child component in Vue.js
Pass dynamic props to child component in Vue.js

Time:11-10

There are two components, main and update modal in my web application. I wanna the modal component can be showed immediately when enter the main page. So, when the main.vue is mounted, showModal is set true. However, the modal does not appear when the web enters the main page. I think showModal becomes true and pass to modal component. When I use vue devtool, it shows popModal is false. It really confuses me.

Should I change the lifecycle which setting the true value or any suggestion?

Thank you!

Main.vue

<template>
  <modal :isShow="showModal"></modal>
  ...
</template>

<script>
export default {
 data () {
   return {
    showModal: false
  }
 }

 mounted() {
  //do something
  this.showModal = true
 }
}
<script>

Modal.vue

<template>
  <modal v-if="popModal" v-model="popModal">
   <p>xxxxxx</p>
   <button @click="fn()">Click</button>
  </modal>
</template>

<script>
export default {
 props: ['isShow'],
 data () {
  return {
   popModal: this.isShow//supposed to be true
  }
 }
 methods: {
  fn() {
    this.popModal = false
  }
 }
}
<script>

CodePudding user response:

The problem is that data is initialized once when the component is created. When the props isShow change, in data the old value remains. You need to add watcher to update data

watch: {
  isShow(newVal, oldVal) {
    // newVal contains the updated value
    // oldVal contains the previous value
    this.popModal = newVal;
  }
}

Or you can make data initialize after the value has changed:

// Main.vue
<modal v-if="showModal" :isShow="showModal"></modal>

// Modal.vue
<modal v-model="popModal">
  • Related