Updating the parent's reference from a child component in Vue 3

In one of my child components, I have a component named Navbar that includes an option for logging out.

<a @click="(event) => {event.preventDefault();}">
  Logout 
</a>

This Navbar component has been imported into my parent component called Home. Within the Home component, there is a div serving as a modal:

<div class="modal" v-if="modal">

The modal will only display when the modal reference is set to true.

<script setup>
import Navbar from './components/Navbar.vue';
import {ref} from 'vue';

const modal = ref(false);

</scipt>

I am curious about how to change the value of the modal reference to true when the user clicks the logout option in the Navbar child component.

Answer №1

Within the main component

<script setup>
    import Navbar from './components/Navbar.vue';
    import {ref} from 'vue';

    const modal = ref(false);

    const setModalTrue= () => this.modal.value = true;        
</script>
<template>
    ....
    <navbar @nav-event="setModalTrue">
    ....
    </navbar>
    ....
</template>

inside navbar component

<script setup>
   const emit = defineEmits(["nav-event"]);
   const sendNavEvent = () => emit("nav-event");
</script>
<template>
    ....
    <a @click.prevent="sendNavEvent">
    ....
    </a>
    ....
</template>

observe @click.prevent=.... - it handles the preventDefault functionality automatically

Answer №2

To trigger an event from the child component, you can add the following code to your Navbar.vue:

<a @click="buttonClick">
  Logout 
</a>

Inside the script setup tag of Navbar.vue:

<script setup>
const emit = defineEmits(['showModal'])

function buttonClick() {
  emit('showModal', true)
}
</script>

Then, in the parent component where you want to use Navbar.vue:

<Navbar @showModal="setModalVisibility" />
.
.
.

<script setup>
function setModalVisibilty() {
  modal.value = true;
}
</script>

Answer №3

Make sure to trigger an event from the Navbar element when the logout link is clicked:

<a @click.prevent="logout">
  Logout 
</a>
<script setup>
import {ref} from 'vue';

const emit=defineEmits(['logout'])

const loggedIn=ref(true)

function logout(){
   emit('logout',!loggedIn.value)
}
</scipt>

Within the parent component:

<Navbar @logout="onLogout" />
<script setup>
import Navbar from './components/Navbar.vue';
import {ref} from 'vue';

const modal = ref(false);

function onLogout(logged){
   modal.value=logged
}
</scipt>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The issue I am experiencing within my PHP code is that the redirection to the gratitude page is not functioning correctly when utilizing

As a newcomer to PHP, I have been struggling with an example code from a website that is not redirecting to the thank you page as expected. Moreover, the email functionality is not working properly either. The code was sourced from: Upon downloading the f ...

Issue encountered when AngularJS struggles to evaluate regular expression within ng-pattern

Currently, I am implementing the ng-pattern argument in an input text field to restrict input to only numeric values: <input type="text" ng-model="numericField" ng-pattern="/^[0-9]*$/" /> However, there seems to be an unusual behavior in the regex ...

Sending both an array and an image via Ajax in a single request

I need to send both JSON and file data to my PHP backend using an ajax call. Here is my current ajax call: $.ajax({ type: 'POST', dataType: 'json', data: jsonData, url: 'xxx.php', cache: false, suc ...

What is the most effective way to inform the user when the nodeJS server can be accessed through socketIO?

I have developed a web app that indicates to the user when the server is online for data submission. Although the current code functions properly for single-user interaction, I am facing an issue where one user's connection or disconnection directly i ...

Tips for effectively utilizing the display:none property to conceal elements and permanently eliminate them from the DOM

While working on my website, I utilized CSS media queries to hide certain elements by using display: none. Even though this effectively hides the element from view, it still lingers in the DOM. Is there a way to completely eliminate the element from the ...

Skipping code in JavaScript/jQuery function on window load

I have created a function that applies specific CSS rules to elements when the window is fully loaded. Check out my code below: function applyHover() { $('.view_preloader .overlay').css('opacity',1); $('.view_pre ...

What is the best way to prevent users from clearing the value attribute of an input element?

Sample Scenario: While a user is entering information into a field, I would like to restrict the ability to delete or clear out the value, such as keeping "Friend" intact. Can this be accomplished using CSS or JavaScript? ...

Is it possible to transform an array of objects into a new array of objects?

After searching for a similar question, I realized none of them really addressed my issue... EDIT: My main goal is to create a reusable dropdown component where I can pass items as props directly. These items need to be objects with both a key (for the fi ...

Does Framework7 have an equivalent to Vue's router.beforeEach() method?

Is there a way to verify the user's token every time the router is accessed in Framework7, similar to Vue's router.beforeEach() method? ...

Javascript/Webpack/React: encountering issues with refs in a particular library

I've encountered a peculiar issue that I've narrowed down to the simplest possible scenario. To provide concrete evidence, I have put together a reproducible repository which you can access here: https://github.com/bmeg/webpack-react-test Here&a ...

The ng-repeat function is iterating through the array multiple times

Using ng-repeat to bind the same array multiple times. JavaScript : $scope.currentitem = item; $scope.currentitemCategory = $scope.currentitem.category.split(','); console.log($scope.currentitemCategory); HTML: <div ng-repea ...

Modify content or display picture within accordion panel based on its identifier

In my view, I have a model representing a list of items. Each item has a unique ID, which is included in the H2 header tag. The details of each item are displayed in a div below the header. Initially, there is an image within the header that is set to disp ...

Encountering permission issues while attempting to add `@nuxtjs/sentry` in a Docker container running Node 16.14. Installation

While attempting to add @nuxtjs/sentry to my project by running npm install @nuxtjs/sentry, I encountered some issues. Here is the error message I received: npm ERR! code 1 npm ERR! path /app/node_modules/@sentry/cli npm ERR! command failed npm ERR! comm ...

Achieving functionality with a fixed header

I am struggling with the scroll functionality and smooth transition in my code for a sticky header. The scroll doesn't work smoothly, especially when the fixed header is activated. The #top-nav-wrapper barely scrolls as expected: <script> $(doc ...

ExpressJS encountered an error due to an unsupported MIME type ('text/html') being used as a stylesheet MIME type

Whenever I start my NodeJS server and enter localhost:8080, I encounter the mentioned error while the page is loading. The head section of my index.html file is provided below. It's puzzling to me why this error is happening, considering that my index ...

Is it possible for a React application to manage errors (status code 4xx) using a try-catch block

Currently delving into React (using hooks) and facing an interesting challenge. I am in the process of building a Notes Application (from FullStackOpen's learn react section). The database I'm working with only allows notes with content length gr ...

Get the PDF in a mobile app using HTML5 and Javascript

For my HTML5/JavaScript-based mobile application, I am in need of implementing a feature that enables users to download a PDF file. The PDF file will be provided to me as a Base64 encoded byte stream. How can I allow users to initiate the download proces ...

Is there a way to achieve this without relying on Ext.getCmp in this particular code snippet?

I am currently using the following code to trigger a button click event once the window show event is called. It works perfectly fine, but I want to achieve the same functionality without using Ext.getCmp. Here is the line of code: Ext.getCmp('recen ...

Ways to execute a JavaScript function upon a button click instead of during the page load completion

I searched on Google but couldn't find the answer, so I'm asking here for help. In the attached screenshot located at the end, when the user clicks on the download button, some backend actions are performed such as file transfer. Once the proces ...

Is it necessary for me to replicate this function? - jQuery

I have developed a function that creates a transparent information overlay on a current div for a mobile web app. Context: I am using jQTouch, which means I have separate divs instead of loading individual pages anew. $(document).ready(function() { ...