Getting a value from a Child component to a Parent component in Nuxt.js - a step-by-step guide

I am facing a challenge in passing data from Child A component to Parent, and then from the Parent to Child B using props.

In my project using nuxt.js, I have the following structure:

layouts/default.vue

The default template loads multiple components which may or may not be used based on a variable from the child component, determining their visibility using the v-if directive.

These child components are the pages such as:

pages/blog/index.vue pages/about/index.vue ...

The objective is for the Child component to determine which components to render on the Parent component. This flag can be changed at any time, allowing the user to choose what is displayed in the admin area.

I have attempted to use local computed methods in the child component as well as vuex, but have not been successful with either approach.

The concept in layouts/default.vue is as follows:

<template>
    <div>
        <TopBar v-if=showTopBar></TopBar>
        <Nav v-if=showNav></Nav>
        etc...
        <nuxt />
    </div>
</template>

<script>

import TopBar from "../components/TopBar";
import Nav from "../components/Nav";
etc...

export default {
    data() {
        return {
            showTopBar: false,
            showNav: false
            etc...
        };
    },
}

</script>


I have already tried using $emit in the child component without success.

In this scenario, the child components are pages, and their layout is determined by a variable fetched from the API. This allows the user to change the layout dynamically.

The goal is to establish a two-way communication between Child Components. For example:

Accessing the route /blog will load the pages/blog/index.vue component.

This component will send a $emit to layout/default.vue indicating which components should be rendered (selected by the user in the admin area and fetched from the API) along with their component ID. (example: {topBar: true, topBarID: 2})

In layouts/default.vue, upon receiving the $emit from pages/blog/index.vue, I would have a value like TopBar: false, and therefore not render it. Alternatively, if the value is true with an ID, that ID will be passed as a prop to TopBar for rendering a customized version created by the user in the admin area.

If possible, could someone provide an example of how to pass this data in this specific scenario? (It doesn't matter if local variables from the Child component or vuex are used, I am simply looking for a way to access the contents of the variable from the Child rather than a plain or undefined object).

PS.: Any suggestions for a better approach to handling dynamic layouts are welcome.

PS2.: I understand that using specific templates for each page, such as layout/blog and layout/contact, would be more structured. However, since the objective is to create a CMS where the user can enable or disable components through a page Wizard similar to Wix, all component customizations will be stored in the database using an ID. Therefore, the idea of defining all possible components and layouts in layout/default.vue seems like a more suitable approach. If there are other ways to achieve the same goal, I would be interested in exploring those options as well.

Answer №1

A more efficient approach would be:

<child-component-1 :showNav.sync="showNav">

Inside the child component, you can update it like this:

this.$emit('update:showNav', value)

The parent component should define this property:

data() {
  return {
    showNav: default_value
  }
}

You need to pass this variable to each child component and define it as a property in each one.

Alternatively, consider creating a simple store within nuxt to store the settings instead.

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

Learning the ropes: Building a model with nodejs using tensorflow.js

I am interested in creating an image classifier, but I lack knowledge of python. Since I am familiar with javascript, I have been considering using Tensorflow.js. Can models be trained with Tensorflow.js, and if so, what are the steps involved in the proce ...

Warning: The current version of graceful-fs (3) is deprecated in npm

I encountered an issue while running npm install. I attempted to run the following command before updating: $npm install npm, and also updated graceful-fs. $ npm install -g graceful-fs <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...

Determine the value of an array element based on a specified

I am in the process of creating an array, currently consisting of a single object that is computed based on other objects from a JSON file. Sampling my code // Retrieve JSON data and convert it to an object let myFile = '{"foo": {"bar": "baz"}, "thu ...

Countdown malfunction: wrong date displayed

Utilizing the Countdownjs library in my project is resulting in an incorrect day count. Incorporating AngularJS, here is the custom directive I've implemented for the countdown: .directive('tempoPercorrido', function($interval){ ret ...

Retrieve data from TypeScript file (.ts) and use it in an HTML document

Recently I started learning Typescript and HTML as I work on building an Angular2 application. At the moment, I have a TypeScript file that resembles the following structure: import {Http, Headers} from 'angular2/http'; import {Component} from & ...

What is the best way to halt the execution of content scripts in the active tab?

I am currently developing a Google Chrome Extension and have come across a bug that I am struggling to fix on my own. The extension works as intended when switching to Youtube's Dark Mode on a single tab. However, if you are on Youtube and open a new ...

What is the best way to reach nested iframes?

I am looking for a solution to send post messages (window.postmessage) to iframes. Currently, it is functioning properly with a single iframe inside the parent page. However, I want it to also work for nested iframes. Here are the criteria: I should on ...

ParcelJs is having trouble resolving the service_worker path when building the web extension manifest v3

Currently, I am in the process of developing a cross-browser extension. One obstacle I have encountered is that Firefox does not yet support service workers, which are essential for Chrome. As a result, I conducted some tests in Chrome only to discover tha ...

React Native's 'onMessage' feature is currently experiencing issues and is not functioning

I'm attempting to retrieve the content of a URL by sending a post message and then listening for it using onMessage, but unfortunately it does not seem to be functioning properly. render(){ const getHtmlJS = "window.postMessage(document.getElementsBy ...

I am looking to display an image as a value in the dropdown menu of my Contact Form 7 on my WordPress website

I am currently working on a Wordpress website where I have a page showcasing 50 different company logos. Below the logo section, there is a form created using Contact Form 7. The logo section was built using a combination of HTML and CSS. Within the form ...

Download the ultimate HTML package with a built-in chart.js component directly from your nuxt app

I have a task to create a compact Nuxt application that produces a basic HTML file containing informative sections about the services offered to the clients of my organization. The main purpose is to generate an HTML file that can be easily downloaded and ...

Sending data from an Ionic application to a server

I came across this solution on a forum, but it lacks detailed explanation for me to customize it according to my requirements. The author also mentions a stack overflow question, which led to various "different" solutions leaving me feeling confused. Belo ...

Unable to access the property 'function' of an undefined value

I've been attempting to call a function from another function within my React application. However, I am encountering an error that reads: Error in login TypeError: Cannot read property 'loadDashboard' of undefined. Despite researching simil ...

What is the best way to address a NULL value within a VueJS filter?

This piece of code demonstrates a working filter filteredItems() { return this.items.filter(item => item.name.toLowerCase().indexOf(this.search.toLowerCase()) > -1) } However, my attempt to filter on a second column ...

jqGrid - Error when the length of colNames and colModel do not match!

Whenever I implement the code below, it triggers an error saying "Length of colNames and <> colModel!" However, if isUserGlobal is false, no errors occur. The version of jqGrid being used is 4.5.4 receivedColModel.push({name:'NAME', index: ...

Guide on implementing hover, click, and other functions with Lottie in NuxtJS

I am currently working with the 'vue-lottie' plugin, but I'm having trouble finding detailed instructions on how to use it. After obtaining JSON animations from Lordicons, I managed to display them correctly. However, I am facing difficulty ...

When trying to click on an HTMLTableRowElement, an Uncaught ReferenceError occurs in React.js and jQuery, stating that the function is

When I was working on my web app, I encountered an issue while trying to create a table. Upon clicking on it, I received an error message: Uncaught ReferenceError: (function) is not defined at HTMLTableRowElement.onclick Here is the code for the table: $( ...

Pass a data variable to an HTML file using express's sendfile function (quick inquiry)

Currently utilizing Node.JS, path, and express for running an HTML webpage. I need to pass a variable to the HTML file for its utilization: var client_cred_access_token = 'fakeToken'; ... app.get('/', function (req, res) { res.se ...

Adding a specialized loader to vue-loader causes issues when the template contains personalized elements

My vue2 component is structured as follows: <template> <p>Hello world</p> </template> <script> export default { name: 'Example' }; </script> <docs> Some documentation... </docs> In addition, I& ...

Obtain the printed value of a button via PHP and manipulate it using JavaScript

I have a dynamic table that displays results from a database. <table id="table" class="table datatable-responsive"> <thead> <tr class="bg-teal"> <th>#</th> <th>Date & Time</th& ...