somebodysomewhere
somebodysomewhere

Reputation: 1146

Vue.js: best practice with managing JS for other components

I have a simple website set up with Vue.js. I have a component for each page (About us, Contact us, etc). Each component fetches the markup for the page via ajax then injects it using <vue-router>.

So far so good.

My question is: what should I do with all the JS that's only used for specific components? My home page might have ~100 lines of JS just for setting up image sliders, hover events, etc. Once I load the About Us component, all that JS for the home page still exists in the browser but it's no longer relevant. Should I manually be nullifying my variables?

What about this case: User visits the Home page, then the About page, then back to Home. On the 2nd visit of the home page, all my old variables still exist, but aren't necessarily in the correct state anymore. I'll want to move sliders back to slide 1, reset any hovers... basically just reset the page.

I guess I'm asking for a very high level overview on how to best manage the JS for multiple components and how it all ties in with document.ready and window.load callbacks once they've already fired and won't fire again. Thanks.

Upvotes: 2

Views: 136

Answers (1)

Eric Guan
Eric Guan

Reputation: 15992

Should I manually be nullifying my variables?

No, this is not a good use of your time/work/effort. Don't worry about performance until it starts to become an issue.

Vue has analogous callbacks for document.ready in the forms of created and mounted, but these are per component whereas document is per.. document?

If you are using the keep-alive wrapper for your router-view, you should use the activated, deactivated callbacks to perform work, such as resetting component state.

If not, then components are destroyed upon leaving the route, and you don't have to reset anything.

As for resetting, i tend to define a function that returns the initial state, and then use this function whenever i need a state reset.

<script>

function initialState(){
    return {
        test:'hi',
    }
}

export default {
    data(){
        ...initialState(),
        hello: 'yoyo', //state that doesn't need to be reset.
    },
    activated(){//user has returned to this route
        Object.assign(this.$data, initialState())
    }
}

</script>

Upvotes: 1

Related Questions