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

No content sent in the request body while implementing fetch

Attempting to send graphql calls from a React component to a PHP server using the fetch method for the first time. The setup involves React JS on the client-side and Symfony 4 on the server-side. Despite indications that data is being sent in the browser ...

Transformation of Array of Objects to Array of Values using Node.js

I am looking to transform the following: [{ prop1: '100', prop2: false, prop3: null, prop4: 'abc' }, { prop1: '102', prop2: false, prop3: null, prop4: 'def' } ] into this format: [[100,false,null,'abc&ap ...

Limit the selected values to calculate a partial sum

Imagine two distinct classes called professor and student: professor.ts export class Professor { id: number name: string } student.ts import { Professor } from "./professor" export class Student { ...

Best practices for updating the value of a specific key within an object that contains recursion in JavaScript/TypeScript

I have a tree component that uses the following data structure type TreeNode = { id: string, parentId: string, renderer: () => React.ReactNode, expanded: boolean, children?: Array<TreeNode>, } Now, I am looking to add functionality for ...

Utilizing HTML5 data attributes to store intricate JSON objects and manipulate them using JavaScript

Recently, I encountered a unique challenge that I set for myself... I am currently in the process of developing an advanced ajax content loader plugin that comes with an array of options and callbacks. In order to streamline the initialization process and ...

Issue: ReactJS + MaterialUI + TypeScript - Property 'component' does not exist?Possible error in ReactJS: component property is

Currently, I am designing my own custom typography. However, I have encountered an error while implementing it. I have been referring to the following documentation: https://mui.com/material-ui/api/typography/ Here is the code snippet that I am using: h ...

Exploring error management in Vue3 and Vite when deploying to production

After following the error handler setup in the Vue documentation, I encountered a difference between using it on the development server and in production. The error handler effectively pinpointed the component and line number where the error occurred durin ...

An error occurs when trying to modify the classList, resulting in an Uncaught TypeError for setting an indexed property

I am attempting to modify the classes of multiple sibling elements when a click event occurs. Some of these elements may have multiple classes, but I always want to change the first class. Below is the code that I created: let classList = event.currentTa ...

Check out the selected values in Ionic 3

I am trying to retrieve all the checked values from a checkbox list in an Ionic3 app when clicked. Below is the code snippet: <ion-content padding> <ion-list> <ion-item *ngFor="let item of items; let i= index"> <ion-label>{{i ...

dc.js bar graph bars blending together

This datetime barChart is causing me some trouble. Interestingly, when I try to replicate the issue in a fiddle (check here), everything functions as expected. Please note that the data takes about 30 seconds to load from github. Below is the code for the ...

Transfer the cropped image to the database through AJAX on the client side and PHP on the server side

I am attempting to upload an image to a Database using JavaScript on the client-side and PHP on the server-side. The first step is selecting an image from the gallery. After zooming and cropping the image, it should be passed to the database. The issue ...

Adding a new column to a table that includes a span element within the td element

I am attempting to add a table column to a table row using the code below: var row2 = $("<tr class='header' />").attr("id", "SiteRow"); row2.append($("<td id='FirstRowSite'><span><img id='Plus' s ...

How can I convert an object array back into an iterated collection after using the find() method in MongoDB?

Currently, I am working on developing an application using AngularJS, NodeJS, and MongoDB. My goal is to load Products classified by ProductCategoryCode sent from AngularJS to NodeJS. The process involves finding Products based on ProductCategoryCode, iter ...

Unraveling Vue Async Components - Harnessing the power of emitted events to resolve

I am looking to create a Vue async component that stays in a loading state until a custom event is triggered. This means it will render a specified loading component until the event occurs. Here's an example of how I want it to work: const AsyncComp ...

Encountering a CORS policy issue while attempting to retrieve data from an API

I have been attempting to retrieve data from the DHL API, however, I keep encountering issues due to CORS policy blocking the request. Even though I have configured the CORS policy on my backend server, the error persists. What could be the issue? Here ...

The `stream.Transform.unshift()` method in Node.js

Let's take a look at this simple example: stream = require 'stream' util = require 'util' class TestTransform extends stream.Transform _transform: (chunk, encoding, callback) -> if not @noMore @noMore ...

Sending a multitude of variables using strings, evaluating them through various functions, and incorporating a variety of methods

To put it simply, my goal is to utilize an object literal that allows me to pass an unknown quantity of variables in any order to a function. While this may seem straightforward in principle, within my code, this object literal is passed to a second functi ...

Testing Vue's disabled input using Vuetify

Learning testing is a new challenge for me, and I'm navigating my way through the complexities of it. Today, I want to create a test for a Vuetify <v-text-field> component with the following structure: <v-text-field v-model="user.c ...

Unable to import createBatchingNetworkInterface from apollo-client

Currently, I am in the process of integrating graphql into my Vue project by following the guidance provided at https://github.com/Akryum/vue-apollo Although I have successfully installed 'apollo-client' via npm as per the requirements, I am enc ...

Unfortunately, CORS is preventing me from sending a POST request through AJAX

I'm currently working on integrating an API into my website. I'm attempting to send a POST request with JSON data, but I keep encountering an error code when trying to make the request. Interestingly, sending the request using curl does not pose ...