Search code examples
vue.jsvuejs2vue-componentvuexvue-router

Single file component - re mount component on changing a value from navbar


This is the structure of my vuejs application.

<template>
    <div class="page-body-wrapper">
        <Sidebar/>
        <div class="main-panel">
            <Header/>
            <div class="content-wrapper">
                <router-view></router-view>
            </div>
        </div>
    </div>
</template>

<script>
    import Header from '../header/header';
    import Sidebar from '../sidebar/sidebar';
    export default {
        name: 'Layout',
        components: {
            Header,
            Sidebar
        }
    }
</script>

In all the routes that are rendered inside <router-view>, i am calling various functions and api calls based on a store variable 'myValue'. And, I have a dropdown in my <Header/> component ( which is common for all routes). Whenever I select a value from the dropdown in header, the store variable 'myValue' changes. Now, I need to remount whatever component is rendered inside <router-view> whenever the store variable 'myValue' changes. Using watch will be a last option since I will have to do the same in a number of components. I cannot use computed, since I have to fetch all data in either 'created' or 'mounted' hook. Is there any option to remount the entire <router-view> when a store variable changes? Note: I am using vuex for state management.


Solution

  • Just pass a key to <router-view :key="myValue"></router-view>, or in your case <router-view :key="$store.state.myValue"></router-view>.

    Also check out this answer.