I have a navbar-item "logout" and I want to call the logout-function which is placed in my Home.vue. The Home.vue component is controlled via router. Is "Navbar" the child and "Home.vue" the parent?
This is my App.vue:
<template>
<div id="app">
<Navbar />
<router-view />
<Footer />
<footer>
<cookie-law theme="base"></cookie-law>
</footer>
</div>
</template>
I've tried all the options listed in stackoverflow but no luck. Please give an example or link to appropriate topic. THX.
CodePudding user response:
I suggest you move the logout function to the component or to the App.vue. and you can call that by emit (component event) in vue.
example:
Navbar.vue
<template>
<div>
<button @click="emitLogoutEvent">Logout</button>
</div>
</template>
<script>
export default {
methods: {
emitLogoutEvent() {
this.$emit("logout");
}
}
};
</script>
App.vue
<template>
<div>
<Navbar @logout="logout"/>
<!-- other code -->
</div>
</template>
<script>
export default {
methods: {
logout() {
// code for logout function
}
}
};
</script>
CodePudding user response:
As per the application design and user case, User can perform Logout
from any page in the application. Hence, Logout functionality should be globally available in the master page (App.vue
) or in the common component (Navbar.vue
) itself. By doing this we no need to write or call the logout logic from each and every component.
As navbar is a common component across the application and contains the logout
button. I think best approach is to handle the logout functionality inside this component itself.
Navbar.vue :
<button @click="logout">Logout</button>
logout() {
// Logout functionlity code. for ex. destroy session or cookie or reset any store data.
// On success navigate the user to the login page
}