Question: How to reinitialize a package on each routing in Vue?

Question

How to reinitialize a package on each routing in Vue?

Answers 1
Added at 2016-12-27 00:12
Tags
Question

I've found a tool for table management and I love it. The only problem is that it needs initializing as shown below, which means that it only gets called once - when the page's been loaded.

mounted: () => {
  $(document).ready(function () { 
    $("table").DataTable();
  }
}

I've put the code in the mounted section and I also tried to use created. For some reason (probably rendering order), I have to keep it in ready method - otherwise it doesn't come up.

This poses two problems for me. Firstly, I'm reusing the same component as a matrix view in multiple components (it's dynamically set up based on the store). Secondly, when I navigate from the page and then go back, it doesn't reinitialize.

How should I make the code inside ready method to run each time the component gets in the view?

I've googled a bit but it's a not so common issue and I'm out of ammo. The best hit I got was the life cycle of the component where I couldn't see anything ground breaking. I also found that the data table instance needs to be destroyed but that only helps if I get to invoke the stuff, which seems not to happen.

Answers to

How to reinitialize a package on each routing in Vue?

nr: #1 dodano: 2016-12-27 07:12

I believe you just need to do following:

mounted () {
    $("table").DataTable();
}

as $(document).ready detects that the document is ready, but in vue case, mounted is called after the instance has just been mounted where el is replaced by the newly created vm.$el, which should be equivalent of document.ready.

I have also checked in vue 2.x.x that mounted gets called if you navigate from the page and then go back.


If this code is dependent on data being loaded and re-rendering of component, you can use updated instead of mounted which is called after a data change causes the virtual DOM to be re-rendered and patched.

updated () {
    $("table").DataTable();
}
Source Show
◀ Wstecz