0

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>

1 Answer 1

3

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">
Sign up to request clarification or add additional context in comments.

2 Comments

What is the value in the first suggested method?
"value" argument is a new value of "isShow" vuejs.org/v2/guide/computed.html#Watchers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.