How to re-mount a component in VueJS?

后端 未结 1 1929
北海茫月
北海茫月 2020-12-05 03:33

I have a component which is mounted as part of the DOM rendering. The skeleton of the application is



  
    &         


        
相关标签:
1条回答
  • 2020-12-05 03:48

    The trick is to alter the key

    When the key changes, vue regards it as a new component, so it will unmount the "old" component, and mount a "new" component.

    See example, the created() hook will only run once, so if you see the value change, you're seeing a brand new object.

    example:

    Vue.component('my-component', {
      template: `<div>{{ rand }}</div>`,
      data() {
        return {
          rand: ''
        }
      },
      created() {
        this.rand = Math.round(Math.random() * 1000)
      }
    });
    
    new Vue({
      el: '#app',
      data: {
        componentKey:0
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.8/vue.min.js"></script>
    
    <div id="app">
      <my-component :key="componentKey"></my-component>
      <button @click="componentKey=!componentKey">press this button to reload the component</button>
    </div>

    0 讨论(0)
提交回复
热议问题