undefined
undefined

Reputation: 6844

Vue JS re-create the root component

I need to destroy and re-create the root application component. This is my template:

<div id="app">
  {{ num }}
</div>

And this is my code:

 if (app) {
      app.$destroy();
    } else {
      app = new Vue(Object.assign({
        el: '#app',
      }, { data: { num: Math.random() } }))
    }

This code runs on button click, but it doesn't clean the template and refresh the new data I'm passing. Any idea why?

Upvotes: 0

Views: 1669

Answers (2)

t.niese
t.niese

Reputation: 40842

I'm pretty sure that your attempt so solve a problem in a way that it should not be solve, or that you use vue in the wrong way.

But to you problem, when you execute this code:

if (app) {
  app.$destroy();
}

Then the documentation state:

Completely destroy a vm. Clean up its connections with other existing vms, unbind all its directives, turn off all event listeners.

So they don't say that the element to wich the vue app is attached to has to or will change. If you want to clean up the DOM then you need to delete the content manually.

After app.$destroy() the app variable will still hold the destroyed vue instance (app wont be magically unset). So another execution of the code will not trigger the else block. You also have to set app to something that evaluates to falsy.

if (app) {
  app.$destroy();
  app = undefined;
}

Now app is undefined so at the next time the if statment is evaluated, the else block would be evaluated and a new instance is created.

Upvotes: 2

Patrick Hollweck
Patrick Hollweck

Reputation: 6665

Your specific use case is not specified in the question, but I assume you want to update something that is not being updated automatically.

To update your component you can use

this.$forceUpdate()

to force a reload of the component.

Upvotes: 0

Related Questions