vuejs / Discussion

Vue.js discussion
166 stars 17 forks source link

for 2 same components with v-if and v-else, mounted hook is only called once #1305

Closed wliyongfeng closed 7 years ago

wliyongfeng commented 7 years ago

For v2.3.0,

HTML code:

<div id="example">
  <my-component text="first" v-if="test"></my-component>
  <!-- expected mounted be called again, but not -->  
  <my-component text="second" v-else></my-component>
</div>

js code:

Vue.component('my-component', {
  template: '<div>{{text}}</div>',
  mounted: function () {
    console.log('mounted')
  },
  props: ['text']
})

new Vue({
  el: '#example',
  data: function () {
    return {
        test: true
    }
  },
  mounted: function () {
    setTimeout(() => {
        this.test = false;
    }, 1000)
  }
})

I expected after the test is set to false, my-component mounted method will be called again, so I can do some initialization. But it doesn't work as that.

Is it designed as that? or a bug?
Could someone give the related implementation(the related code)?

wliyongfeng commented 7 years ago

It can be solved by this

https://vuejs.org/v2/guide/conditional.html#Controlling-Reusable-Elements-with-key